Reputation: 89
In the book Core Java Ⅰ, it says ...
protected
keywords should be carefully used. If you set a class with aprotected
field, than, if you want to change it, you must notify all programmers who use this class.
I can not understand. If Son extends Father
, and Father
has changed, Son
has not been affected. Is it right?
Upvotes: 4
Views: 208
Reputation: 2289
I can not understand. If
Son extends Father
, andFather
has changed,Son
has not been affected. is it right?
Short answer is: No, for the general case!
Suppose you have the two classes you describe in version 1 of your source code:
class Father { protected int asdf; }
class Son extends Father { int qwer = 2 * asdf; }
Now lets change the protected field asdf
of the Father
class Father { protected int fdsa; }
class Son extends Father { int qwer = 2 * asdf; } // compile error
Now you MUST change the Son
as well, so it definitely affects the sub class.
Let's think about a library, we assume you are using a lot. Let's say you have derived 20 classes from the core library classes. With the next update of the library your 20 classes might gonna have to change as well. This is because protected breaks encapsulation.
There are several good resources depicting all the nifty details about this issue, a nice summation can be found here on programmers SE network. I try to summarize it even more now.
Using protected
tends to;
Another good reference is Clean Code from Robert C. Martin (alias Uncle Bob).
Upvotes: 1
Reputation: 7867
Example: If father has a safe and gives his son the combination. The son can take money from the safe without notifying the father, or the other way around. Either way, there is no guarantee that the son, taking money from the safe will communicate that to the father.
On the other hand, if the son always asks the father for money, then father can track spending and control how the money is spent.
This is equivalent to encapsulation. It is always a best practice to keep fields private and expose public or protected methods. This way, the person responsible (where the field is declared) can hide the details of how the field is modified, but can give access to information that is relative to the caller of the method.
This also shields changes in the future. For example, lets say you have a field called total. If you give direct access to the field, you can't guarantee the field has not been modified incorrectly and a bug introduced. If however, you only give access via a method() you could change how the calculation is performed and anyone who calls the method is not affected and benefits from the change.
Upvotes: 6