简体   繁体   English

Java中的间接子类无法访问超类中的受保护成员

[英]Protected members in a superclass inaccessible by indirect subclass in Java

Why is it that in Java, a superclass' protected members are inaccessible by an indirect subclass in a different package? 为什么在Java中,超类的受保护成员是不可被另一个包中的间接子类访问的? I know that a direct subclass in a different package 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 它打印1

As you see, the attribute a is accessible from subclass C . 如您所见,属性a可从子类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.
    }


}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM