小斌斌来也
小斌斌来也

Reputation: 89

Why carefully use "protected"

In the book Core Java Ⅰ, it says ...

protected keywords should be carefully used. If you set a class with a protected 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

Answers (2)

isaias-b
isaias-b

Reputation: 2289

I can not understand. If Son extends Father, and Father 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:

Version 1

class Father { protected int asdf; }
class Son extends Father { int qwer = 2 * asdf; }

Now lets change the protected field asdf of the Father

Version 2

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.

Libraries

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.

Further Reading

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;

  1. lead to YAGNI issues.
  2. lead to LSP issues.
  3. violate OCP.
  4. design where inheritance is favored over composition.
  5. lead to more violation of the SRP.

Another good reference is Clean Code from Robert C. Martin (alias Uncle Bob).

Upvotes: 1

pczeus
pczeus

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

Related Questions