Possible Duplicate:
In Java, what's the difference between public, default, protected, and private?
Why can't a subclass in one package access the protected member of it's superclass (in another package) by the reference of the superclass? I am struggling with this point. Please help me
package points;
public class Point {
protected int x, y;
}
package threePoint;
import points.Point;
public class Point3d extends Point {
protected int z;
public void delta(Point p) {
p.x += this.x; // compile-time error: cannot access p.x
p.y += this.y; // compile-time error: cannot access p.y
}
A protected member can be accessed by the class, other classes in the package and implicitly by its subclasses. i.e., the subclass can access x from its own parent.
The fact that you are able to access this.x proves that x from the superclass is accessible. If x were private in the superclass, this.x would give an error.
When you say p.x you are trying to access some other instance's x, and not in its own hierarchy. This is not allowed outside the package.
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