re: What is the difference between public, protected, and private in Java? VIEW POST


Well I would have agreed a few years ago but now I've been coding in many languages and it appears that this strategy isn't really useful in my opinion.

In Java if you want to keep your sanity then use interfaces as much as possible to define types. And since the interface is the minimal promise you make to the outside world, just set everything to public.

Also, only declare methods in interfaces (yeah the getters/setters debate)

And finally, everything in the same code base should be able to access "publicly" everything else from that same code base. It's safe because your IDE will tell you about any mistake you make. And it saves you mental load.


How can the IDE tell me about mistakes in this case? When everything is public there are no access related mistakes.


Well private fields are private because you don't want to guarantee internal structure to outsiders so if you change it other apps don't get broken.

Here if you change something you're going to break the compilation so you're basically going to notice that you've broken your app/lib. Thus you are pretty safe.

While this makes sense, I still don't get your point.

If I understand you correctly, you suggest to make all fields and methods of a class public because encapsulation does not provide much value.

This means that every part of your codebase is potentially directly connected to any other part. How do you keep the design from turning into a Big Ball of Mud? You mention interfaces. But how do you make sure everybody uses them and does not access the classes directly?


And finally, everything in the same code base should be able to access "publicly" everything else from that same code base.

No, just please no. You really shouldn't expose everything. That's just nonsense. You should expose carefully and use the least access modifier possible in any case. If you develop a library, you shouldn't expose the whole of it for the client, because:

  • he could mess up
  • if you provide a thin interface, it's easier to understand

Also look at the top of your source files. How many import do you see? Not the whole codebase I guess. That's because when you use something then you'll start depending on it. And you don't want to depend on the whole codebase. Use private fields, private inner classes if needed. Don't let your own code to fool you or anyone else, be defensive.

Code of Conduct Report abuse