【问题标题】:protected access type [duplicate]受保护的访问类型 [重复]
【发布时间】:2012-08-08 14:17:45
【问题描述】:

可能重复:
In Java, what's the difference between public, default, protected, and private?

为什么一个包中的子类不能通过超类的引用访问它的超类(在另一个包中)的受保护成员?我正在为此苦苦挣扎 观点。请帮帮我

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

  }

【问题讨论】:

    标签: java subclass access-specifier


    【解决方案1】:

    类、包中的其他类以及其子类可以隐式访问受保护的成员。即,子类可以从它自己的父类访问x

    您能够访问this.x 的事实证明超类中的x 是可访问的。如果x 在超类中是私有的,this.x 会报错。

    当您说p.x 时,您是在尝试访问其他实例的x,而不是在它自己的层次结构中。这在包外是不允许的。

    【讨论】:

      【解决方案2】:

      因为您引用了Point不同 实例的成员。这是不允许的。

      您当然可以像使用 this.x 一样访问继承的成员。

      【讨论】:

        猜你喜欢
        • 2011-09-22
        • 2019-05-07
        • 2012-05-26
        • 1970-01-01
        • 2012-05-26
        • 2012-11-20
        • 2015-11-04
        • 2013-11-23
        • 1970-01-01
        相关资源
        最近更新 更多