Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would an OO language really need a PROTECTED access modifier?

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)

like image 388
Mecki Avatar asked Dec 03 '22 10:12

Mecki


1 Answers

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.

like image 83
Bozho Avatar answered Apr 27 '23 19:04

Bozho