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

问题描述

我想就此进行一些讨论,但我无法推断出我案例的答案。仍然需要帮助。

I want some discussions about this, but I could not infer the answer for my case. Still need help.

这是我的代码:

package JustRandomPackage;

public class YetAnotherClass{
    protected int variable = 5;
}





package FirstChapter;

import JustRandomPackage.*;

public class ATypeNameProgram extends YetAnotherClass{
    public static void main(String[] args) {

        YetAnotherClass bill = new YetAnotherClass();
        System.out.println(bill.variable); // error: YetAnotherClass.variable is not visible

    }
}

以下一些定义,上面的示例似乎令人困惑:

Some definitions following which, the example above seems to be confusing:

 1. Subclass is a class that extends another class.
 2. Class members declared as protected can be accessed from
    the classes in the same package as well as classes in other packages
    that are subclasses of the declaring class.

问题:为什么我无法访问受保护的成员( int variable = 5 )来自子类 YetAnotherClass 实例( bill 对象)?

The question: Why can't I access the protected member (int variable = 5) from a subclass YetAnotherClass instance (bill object)?

推荐答案

作为声明类的子类的其他包中的类只能访问自己继承的 protected members。

Classes in other packages that are subclasses of the declaring class can only access their own inherited protected members.

public class ATypeNameProgram extends YetAnotherClass{
    public ATypeNameProgram() {
        System.out.println(this.variable); // this.variable is visible
    }
}

...但是不是其他对象的继承受保护的成员。

... but not other objects' inherited protected members.

public class ATypeNameProgram extends YetAnotherClass{
    public ATypeNameProgram() {
        System.out.println(this.variable); // this.variable is visible
    }

    public boolean equals(ATypeNameProgram other) {
        return this.variable == other.variable; // error: YetAnotherClass.variable is not visible
    }
}

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

06-10 05:09