As someone learning Java from scratch, who knows a little Python, I have been wondering whats with all the access modifiers (public, static, protected…) in Java. I know what they mean, but why use them?
It’s just something that’s been bugging me, because whenever I write a new class and I write the instance variables I constantly have to ask myself do I want this variable to be private, public, final etc? I usually come to the conclusion I dont care for the majority of varibles and methods. There are a few instances where I know I will need to call the method from another class, but why not just make all methods public? Is it because in large projects you cant trust another developer isn’t going to start rummaging around and messing up your code?
Use the minimal visibility modifier in each case. For example fields should be private in almost all cases.
Methods can be:
These all relate to API design – what functionality you want your API to expose and what not. That is – which methods are internal to your implementation, and which should be usable by classes that use your class to do their job.
The advantage of all this is that you can change private/package-private methods without anyone else but your own class/package relying on them. Making them public ties you to supporting them. This is true not only when you are designing an API like the collections framework. It’s also true when you design your own API inside your own project. Classes have to be aware of much less methods (and hence are easier to change and support).
See this presentation by Joshua Bloch on API design (specifically from 29:00)