My question relates to Java, but it also can be applied to C#. I was wondering why everybody recommends making the instance variables private as opposed to making them protected.
Let's just think about it. Private variables are not seen by the subclass, so if I need to access or change the variables of the superclass in my subclass I am forced to use some accessor and mutators method like getMyPrivateVariable
or setMyPrivateVariable
. But when you extend some class and inherit its members, this works as if you have declared them in the subclass directly. So logically this means that the subclass should also have direct access to the instance variables and makes a case for designing the class with protected variables. I understand that such a practice would break encapsulation but this seems irrelevant in the case of inheritance, because, again, in this case everything works as if the members of the superclass were declared in the sublcass, so the sublcass has a "natural right" for being able to access its members directly, no matter if they were inherited or not. Encapsulation, in my opinion, is more important for interfacing with the object by other objects that are outside of the object's inheritance tree.
So, my question is why everyone recommends declaring instance variables of the class as private as opposed to protected?
You answer it yourself - encapsulation.
For example you have an abstract Cat class. This defines the member variable speed - i.e. how fast it's running.
The abstract class also defines a final method of run which obviously updates speed.
Now - if subclasses of Cat - e.g. Moggy or Tabby could access and modifiy "speed" directly then it could break the run method.
So best to keep it tied up where it begins. You can also declare it locally if you need to.
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