Protected access in Java should be used very sparingly

Alonso Del Arte
5 min readApr 2, 2024
Photo by Tiard Schulz on Unsplash

Yesterday I was reviewing a Java program of mine that I’ve been working on a few years now. A friend of mine, who is quite proficient with Swift, asked me about the protected access level in Java.

In that very moment I realized that my choice of access level all those years ago had been wrong, and also that following the single responsibility principle generally leads to our having very little use for the protected access level.

Although the rules for protected access in Java are much simpler than protected access in C++, Java’s protected access still sits somewhat uncomfortably between public and package private access.

For Java 8 and before, public meant accessible from anywhere: from the same class, from a class in the same package, from a class in a different package, etc. With modules in Java 9 and later, there are some caveats to public, but the basic principle remains the same.

In classes, public access must be explicitly indicated in classes with the reserved word public. For interfaces, public access is mostly tacit.

Package private means the same thing in all versions of Java so far: accessible only in the same package.

That’s fairly easy to understand. If something is package private in the org.example package…

--

--

Alonso Del Arte

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