protected access type

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. ie, 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 px you are trying to access some other instance's x , and not in its own hierarchy. This is not allowed outside the package.


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 .

链接地址: http://www.djcxy.com/p/24070.html

上一篇: 公共无效和无效方法有什么区别?

下一篇: 保护访问类型