This week's book giveaway is in the OCAJP forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide 1Z0-808 and have Jeanne Boyarsky & Scott Selikoff on-line! See this thread for details.
OK - here's my problem. I've just read through the explanation of the protected modifier in the SCJP Exam Guide (by Kathy Sierra and Bert Bates). I thought I had finally understood the protected modifier until I read the very last paragraph which says "it's only used in very special cases".
That's when my understanding came crashing down in a heap. I believe it is good practice to encapsulate access to instance variables. For example:
The variables are private and the get, set methods are used to access the values. OK, so far so good.
Now, what if I want to create a class in another package that extends Dog ?
To my understanding, Spaniel will inherit the getWeight and setWeight methods of the Dog class (because they are public) but WILL NOT inherit the weight variable because it is private.
So my question is: what good is it if I inherit the getter and setter methods but not the variable itself ?
Does this mean that I have to declare instance variables as protected if I want them to be inherited by classes in other packages ?
If that is the case, then why do the authors of the SCJP exam guide say that protected is used very rarely ?
I guess I am missing something very obvious here. I also cannot believe how much confusion the protected keyword causes. I've been learning java for many months and I still haven't read a satisfactory explanation.
Thanks in advance for your help with this toughie.
A subclass cannot inherit the private members of the superclass. Does this mean that all of the members that you wish to be 'inheritable' should be marked as protected ?
This is not quite true. A subclass inherits all members of the superclass. However, it cannot directly access private members of the superclass. In your example where the superclass provides setters and getters for the private members, the subclass can access them indirectly through these members. Notice that the private members still exist (i.e. there is memory allocated for them).