Java Access Modifiers – When to Use Default Access Modifier

access-modifiersjava

I want to understand, from design point of view, in what situations I should use default access modifier, and when I shouldn't.

I found this related question, that provides some basic explanations, how ever I am searching for an answer that will target encapsulation and single reason of change principles, and address it in more professional way.

Best Answer

The default access is otherwise known as package level private or protected... your choice, it doesn't really have a term, but its useful to think of it that way.

If you dig within the source for java.lang you will often see it - allowing other classes within java lang to be able to access some of the internals of this class without exposing those internals to all of the world.

Just glancing, an example of this is the sizeTable within java.lang.Integer (grepcode) that allows there to be a single point where this information is stored. As this is associated with stringSize (just below it) that is likely used within java.lang.String it means that one doesn't have to have two copies of it or expose it. Other methods in the area also show more of this Integer/String relationship.

Thinking about this more, you've got Integer.toString(int i) and String.valueOf(int i) - both of which do very similar things. While its debatable if you want to have the ability to do the same thing in two classes... if you do, you only want to have the code in one place - which again points you to having a package level encapsulation.

Putting things within the same package is supposed to be an important part of encapsulation. The classes within a package are supposed to work closely with each other. It means these classes should be able to look at each other's internals and work with them. It avoids having java.lang.FunkyStringConstatns sitting out there for all the world to see... and once the world sees it as something public, it means that one can't go and change it.

This has less meaning when one works on the entire project from start to finish and there is no public API. Its more a 'yea, its there' then. But if you are working on public APIs, you will want times to be able to share data without sharing it with the world.