来自超类的受保护变量在不同包中的子类中不可见

时间:2013-12-12 04:21:58

标签: 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和命令提示符执行此代码。

任何人都可以请看看这个

1 个答案:

答案 0 :(得分:2)

作为声明类的子类的其他包中的类只能访问自己继承的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?