java - 来自父类(super class)的 protected 变量对于不同包中的子类不可见

标签 java eclipse

我在不同的包中有两个类,如下所示 这是包库中的基类。

package library;

public class Book{

    public int varPublic;
    protected int varProtected;
    private int varPrivate;
    int varDefault;
}

这是包构建中的子类。

package building;

import library.Book;

public class StoryBook extends Book {


    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Book book = new Book();
        book.varPublic = 10;
        book.varProtected = 11;


    }

}

我的理解是变量“var.Protected”应该在 StoryBook 类中可见,但我收到错误。我尝试从 eclipse 和命令提示符执行此代码。

有人可以调查一下吗

最佳答案

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

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

...但不是其他对象继承的 protected 成员。

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

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

也请阅读这篇文章

<强> Why a protected member of a superclass can't be accessed from a subclass by using a superclass' reference?

关于java - 来自父类(super class)的 protected 变量对于不同包中的子类不可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20534990/

相关文章:

java - 为什么此 HQL 搜索查询不起作用?

java - 解决 javax.net.ssl.SSLHandshakeException : sun. security.validator.ValidatorException : PKIX path building failed Error?

java - 避免使用 ant 并通过 eclipse 自动构建。这可能吗?

java - Keytool 插件 Eclipse 不工作

Java - 处理程序终止

java - 如何增加catch block 中的值?

java - 定宽 float 格式

java - 在 AlertDialog 中调用方法时出错

eclipse - 在 GWT 2.1.0.M2 中,无法识别选项 "-style pretty"

java - 调试时无法解析类