开发者

Protected members in a superclass inaccessible by indirect subclass in Java

开发者 https://www.devze.com 2022-12-30 14:54 出处:网络
Why is it that in Java, a superclass\' protected members are inaccessible by an indirect subclass in a different package? I know that a direct subclass in a different p开发者_C百科ackage can access th

Why is it that in Java, a superclass' protected members are inaccessible by an indirect subclass in a different package? I know that a direct subclass in a different p开发者_C百科ackage can access the superclass' protected members. I thought any subclass can access its inherited protected members.

EDIT

Sorry novice mistake, subclasses can access an indirect superclasses' protected members.


Perhaps you're a little confused.

Here's my quick demo and shows an indirect subclass accessing a protected attribute:

// A.java
package a;
public class A {
    protected int a;
}

// B.java 
package b;   //<-- intermediate subclass
import a.A;
public class B extends A {
}

// C.java
package c; //<-- different package 
import b.B;
public class C extends B  { // <-- C is an indirect sub class of A 
    void testIt(){
        a++;
        System.out.println( this.a );//<-- Inherited from class A
    }
    public static void main( String [] args ) {
        C c = new C();
        c.testIt();
    }
}

it prints 1

As you see, the attribute a is accessible from subclass C.

If you show us the code you're trying we can figure out where your confusion is.


Maybe the problem is that he try to access the protected field of other instance but not his. such like:

package a;
public class A{
    protected int a;
}

package b;
public class B extends A{

}

package c;
public class C extends B{
    public void accessField(){
        A ancient = new A();
        ancient.a = 2;  //That wouldn't work.

        a = 2;   //That works.
    }


}
0

精彩评论

暂无评论...
验证码 换一张
取 消