2

I have an instance variable in the class Avo, package ger1, with protected modifier.

package ger1;  

public class Avo {  
    protected int i = 1;  
}

Then I have a class Pai which is in package ger2, extends Avo and accesses the variable by instance, so far normal...

package ger2;  

public class Pai extends Avo {  
    public Pai() {  
        i++  
    }  
}  

But Kathy Sierra's book says of the protected member, "Once the subclass-outside-the-package inherits the protected member, that member (as inherited by the subclass) becomes private to any code outside the subclass, with the exception of subclasses of the subclass."

But if i try to access the member through instance of class Pai it's allowed! However the Filho class must be in the same package of Avo. Why this? It's normal?

package ger1;  

import ger2.Pai;  

public class Filho {  
    public Filho() {  
        Pai pai = new Pai();  
        pai.i++;  
    }  
} 
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
Andrey
  • 2,485
  • 3
  • 21
  • 26
  • 1
    Could you provide a reference (as in, a link or something like that) to the book you mean? In the meantime, to clear up questions on access modifiers, I'd recommend the java tutorials http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html – G. Bach Aug 31 '12 at 00:33
  • The book is "Sun Certified Programmer for Java 6 Study Guide" by Kathy Sierra, page 36. – Andrey Aug 31 '12 at 00:40

2 Answers2

0

This is expected behavior. "protected" means visible in sub-classes, even if they are in a separate package.

Edit: see also this question In Java, difference between default, public, protected, and private

Community
  • 1
  • 1
noahlz
  • 10,202
  • 7
  • 56
  • 75
  • 1
    Correct, but I think he asked if whether a protected attribute is visible or not to a non sub-class of the same package (which is also true). – fgp Aug 31 '12 at 00:42
  • Even through instance (not by inheritance), for another class that inherits the protected member in another package? – Andrey Aug 31 '12 at 00:43
  • Yes, which is why I linked to the other question, which provides a much more detailed answer. See the answer with over 300 upvotes. – noahlz Aug 31 '12 at 02:04
0

Your call to pai.i++; is made in the ger1 package.

Your protected int value is declared in the ger1 package, meaning the same as above.

So, i is reachable since protected values are accessible by all class residing in the same package.

To expect the case that the Kathy Sierra's book wrote, just move the Filho class from ger1 package to ger2 package.

So that you will notice that i appeared unreachable :)

Mik378
  • 21,881
  • 15
  • 82
  • 180