I want some discussions about this, but I could not infer the answer for my case. Still need help.
Here is my code:
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
}
}
Some definitions following which, the example above seems to be confusing:
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.
The question: Why can't I access the protected member (int variable = 5
) from a subclass YetAnotherClass
instance (bill
object)?
Classes in other packages that are subclasses of the declaring class can only access their own inherited protected
members.
package FirstChapter;
import JustRandomPackage.*;
public class ATypeNameProgram extends YetAnotherClass{
public ATypeNameProgram() {
System.out.println(this.variable); // this.variable is visible
}
}
... but not other objects' inherited protected
members.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With