Java access modifiers: which to choose when, and why

Alonso Del Arte
21 min readJan 9, 2021
Photo by Michael Dziedzic on Unsplash

On one of those question-and-answer websites, someone asked: What is the point of Java access modifiers if you can always just change them? It’s a question that crossed my mind when I was starting to learn Java years ago.

The student learns what the access modifiers are, and their semantics. And hopefully the student is given some guidance as to how to choose a modifier in the most common situations.

For this article, I assume you already know what the access modifiers are. If not, I wrote another article which only covers the basics, without any comment on the rationale for choosing one modifier and not another.

To a Java beginner, the access levels suggest levels of information security. But then this is not a very secure system, because anyone who can edit the source can change the access modifiers.

It’s also possible, but more complicated, to bypass access modifiers using platform-dependent subroutines, or “native methods.” The access modifiers can also be changed in the bytecode for the Java Virtual Machine (JVM).

That’s the wrong way to look at it. Access modifiers don’t indicate levels of information security, but rather they declare your intentions in regards to encapsulation. Access modifiers enable the Java compiler and other tools to enforce…

--

--

Alonso Del Arte
Alonso Del Arte

Written by Alonso Del Arte

is a Java and Scala developer from Detroit, Michigan. AWS Cloud Practitioner Foundational certified

No responses yet