Java – Why did Java make package access default

access-modifiersencapsulationjavalanguage-specificationsunit testing

I'm asking this question because I believe they did it for a very good reason and that most people do not use it properly, well from my experience in industry so far anyway.
But if my theory is true then I'm not sure why they included the private access modifier…?

I believe that if default access is properly used it provides enhanced testability whilst maintaining encapsulation. And it also renders the private access modifier redundant.

The default access modifier can be used to provide the same affect by using a unique package for methods that need to be hidden from the rest of the world, and it does this without compromising testability, as packages in a test folder, with the same are able to access all the default methods declared in a source folder.

I believe this is why Java uses package access as 'default'. But I'm not sure why they also included private access, I'm sure there is a valid use case…

Best Answer

I guess they had a good idea of what an average programmer would do. And by average programmer I mean one who is not really good at programming, but gets the job anyway because there are not enough good ones and they are expensive.

If they made "public" access the default one, most programmers would never bother to use anything else. The result would be a lot of spaghetti code everywhere. (Because if you are technically allowed to call anything from anywhere, why ever bother to encapsulate some logic within a method?)

Making "private" the default access would only be slightly better. Most beginning programmers would simply invent (and share on their blogs) a rule of thumb that "you need to write 'public' everywhere", and then they would complain why Java is so bad that it forces them to write "public" everywhere. And they would also produce a lot of spaghetti code.

The package access is something that allows programmers to use their sloppy programming techniques while writing code within one package, but then they have to reconsider it when making more packages. It is a compromise between good business practices and the ugly reality. Like: write some spaghetti code, if you insist, but please leave the ugly mess within the package; at least create some nicer interfaces among the packages.

Probably there are other reasons, too, but I wouldn't underestimate this one.

Related Topic