Access protected member

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++;  
    }  
} 

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


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 :)

链接地址: http://www.djcxy.com/p/24112.html

上一篇: 了解java的受保护的修饰符

下一篇: 访问受保护成员