I'd always (incorrectly) believed that, if you didn't specify the visibility of an attribute or method in a Java class, it'd be private in the former case and public in the latter. This is not what really happens. In fact, Java has four different visibility modifiers: public, protected, private and "package". The first three are the "standard" OOP types, while the last one is Java specific.
There is no reserved keyword in the Java language to denote an attribute or method as "package"-visible; this status is automatically assigned when no modifier is applied. But... what does it mean? Consider a Foo class with an attribute bar and a methodbaz, both with the default visibility set. Any other class in the same package as Foo will be able to freely access bar and baz. In the other hand, classes from other pacakges will see bar and baz private.
Aren't you thinking about C++'s friend keyword by now? Exactly! This default visibility status can be used to achieve a similar thing in Java. Just put the classes with a friendship relation in the same package and they will be able to interact with each other, sharing implementation details without exposing them to the public.
Want more posts like this one? Take a moment to subscribe!
Enjoyed this article? Spread the word or join the ongoing discussion!