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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2820630/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 22:59:27  来源:igfitidea点击:

Protected members in a superclass inaccessible by indirect subclass in Java

javainheritancepackagesprotected

提问by MSumulong

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 package can access the superclass' protected members. I thought any subclass can access its inherited protected members.

为什么在 Java 中,不同包中的间接子类无法访问超类的受保护成员?我知道不同包中的直接子类可以访问超类的受保护成员。我认为任何子类都可以访问其继承的受保护成员。

EDIT

编辑

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

抱歉新手错误,子类可以访问间接超类的受保护成员。

回答by OscarRyz

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 ais accessible from subclass C.

如您所见,该属性a可从 subclass 访问C

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

如果您向我们展示您正在尝试的代码,我们可以找出您的困惑所在。

回答by YiFan Wu

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.
    }


}