来自超级类的受保护变量在不同包中的子类不可见 [英] protected variable from super class not visible from subclass in different package
问题描述
我有两个类在不同的包中如下
这是包库中的基类。
I have two classes in different packages as follows This is the base class in package library.
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和命令提示符执行这个代码。
my understanding is that the variable "var.Protected" should be visible in the class StoryBook but i am getting an error. I have tried to execute this code from eclipse and command-prompt.
任何人都可以查看这个
推荐答案
作为声明类的子类的其他包中的类只能访问自己继承的保护的
成员。
Classes in other packages that are subclasses of the declaring class can only access their own inherited protected
members.
public class StoryBook extends Book {
public StoryBook() {
System.out.println(this.variable); // this.variable is visible
}
}
...但不是其他对象的继承保护
成员。
... but not other objects' inherited protected
members.
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?
这篇关于来自超级类的受保护变量在不同包中的子类不可见的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!