I can understand why there is public and private access modifier, these two are also found in almost any language. I can even understand why there might be a package modifier, as you may want to have your classes (those that tightly belong together) interact with each other in a way, that is not suitable for public interaction (e.g. as it depends upon knowledge of class internals, maybe because it would reveal a secret, or maybe because it may change at any time and relying on it will break all existing code, and so on). However, why would I want to have a protected identifier? Don't get me wrong, I know what protected means, but why would I want subclasses of my classes to access certain instance variables or use certain methods, just because they are subclasses and even if they are part of a different package? What is a real world use case for protected?
(And performance as an argument for instance variables does not count, since a JIT compiler can always inline accessor methods, decreasing their call overhead to zero)
Public methods are part of the public interface. Private methods are internals. Protected methods are points of extension.
With protected
you can redefine the functioning of a class by overriding it without making this method part of the public interface.
Another thing - protected methods are common methods that can be reused by subclasses, but again don't need to be part of the public interface.
For example, in the java collection framework, there is the the AbstractList
class. It has protected modCount
field and a protected removeRange
method:
the modCount
field is used (incremented) by all subclasses to count the number of modifications. The Iterator
returned by AbstractList
makes use of that field
the removeRange
method can be reused by subclasses, instead of having them define it again.
See this related presentation by Josh Bloch on API design.
As noted in the comments, and in the presentation by Bloch - document your class well. And if it is meant for inheritance - make extra effort.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With