3

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

  }
Community
  • 1
  • 1
vijay
  • 321
  • 1
  • 3
  • 5

2 Answers2

8

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.

Nivas
  • 18,126
  • 4
  • 62
  • 76
1

Because you reference the members of a different instance of Point. This is not allowed.

You can of course access the inherited members as you do with this.x.