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