Question:
Why does an error occur in the commented out line, because protected subclasses of the class are available to classes in the same package, and to subclasses in other packages.
package one;
public class One {
protected int val;
}
If you create the same class in package one
, then there will be no error in the commented out line. For a static
variable, there will be no error in both cases.
package two;
import one.One;
public class Two extends One{
private One o = new One();
//private int val = o.val;
}
Answer:
At first glance, the error in your code is not visible, but it is there.
You're right, protected
properties are available to descendants in other packages. But look at how you refer to the parent from Two
:
private One o = new One();
You are not using family ties here. You just created a new instance of the class, not related in any way to yours. If you want to refer to the parent class, you should use the super
keyword:
private int val = super.val;