Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should not declare a variable protected for inheritance?

I have read from literature that a variable shouldn't be declared protected just so it could remain visible in the inheritance tree.

Why is so?

like image 826
Oh Chin Boon Avatar asked Dec 04 '22 06:12

Oh Chin Boon


2 Answers

Fields are implementation details - they should not generally be regarded as part of the API - that way you get to change exactly how things are stored later on. If you make a field protected, it will be available to subclasses, rather than the subclass only getting to see an API which they can rely on.

What if you want to restrict which values are valid on that field at a later date? When it's protected, you don't get any validation or anything similar. Subclasses could put any old rubbish in there. If you keep it private and give a protected setter method, you can apply appropriate validation.

In short: regard your clients-through-subclassing as clients in much the same way as your clients-through-calling. Give them an API to work with, and keep your implementation details private.

like image 119
Jon Skeet Avatar answered Dec 05 '22 20:12

Jon Skeet


Most of the times, when I create inheritance, I make sure that all variables are private. Whenever the inherited class wants to have something from the super class, he can get the values with the getter methods.

If everyone could get and set a variable in the hardcore way, there is no way to rely on extra code that should be run when you set that variable. The super class is giving away his own responsibilities.

like image 21
Marnix Avatar answered Dec 05 '22 18:12

Marnix