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 ?
For example:
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.