Java中的间接子类无法访问超类中的受保护成员 [英] Protected members in a superclass inaccessible by indirect subclass in Java

查看:198
本文介绍了Java中的间接子类无法访问超类中的受保护成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

编辑

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

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

推荐答案

也许你有点困惑。

这是我的快速演示并显示访问受保护属性的间接子类:

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();
    }
}

打印1

如您所见,属性 a 可从子类 C 访问。

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.

这篇关于Java中的间接子类无法访问超类中的受保护成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆