我想对此进行一些讨论,但无法推断出我的情况的答案。仍然需要帮助。
这是我的代码:
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 } }
在上面的示例中,下面的一些定义似乎令人困惑:
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对象)访问受保护的成员()?
int variable = 5
YetAnotherClass
bill
作为声明类的子类的其他包中的类只能访问其自己的继承protected成员。
protected
package FirstChapter; import JustRandomPackage.*; public class ATypeNameProgram extends YetAnotherClass{ public ATypeNameProgram() { System.out.println(this.variable); // this.variable is visible } }
…但不是其他对象的继承protected成员。
package FirstChapter; import JustRandomPackage.*; 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 } }