【问题标题】:Why isn't protected field visible to a subclass? [duplicate]为什么子类看不到受保护的字段? [复制]
【发布时间】:2015-09-05 11:46:33
【问题描述】:

我有一堂课:

package foo;
public abstract class AbstractClause<T>{
    protected T item;
    protected AbstractClause<T> next;
}

及其子类(在不同的包中):

package bar;
import foo.AbstractClause;

public class ConcreteClause extends AbstractClause<String>{

    public void someMethod(ConcreteClause c) {
        System.out.println(this.next);      // works fine
        System.out.println(c.next);         // also works fine
        System.out.println(this.next.next); // Error: next is not visible
    }
}

为什么?

【问题讨论】:

标签: java class


【解决方案1】:

似乎如果子类在不同的包中,那么方法只能访问自己的受保护实例字段,而不能访问同一类的其他实例的那些。因此this.lastthis.next 工作,因为它们访问this 对象的字段,但this.last.nextthis.next.last 将不起作用。

public void append(RestrictionClauseItem item) {
    AbstractClause<Concrete> c = this.last.next; //Error: next is not visible
    AbstractClause<Concrete> d = this.next; //next is visible!
    //Some other staff
}

编辑 - 我不太对。无论如何感谢您的支持:)

我尝试了一个实验。我有这门课:

public class Vehicle {
    protected int numberOfWheels;
}

而这个在一个不同的包中

public class Car extends Vehicle {

  public void method(Car otherCar, Vehicle otherVehicle) {
    System.out.println(this.numberOfWheels);
    System.out.println(otherCar.numberOfWheels);
    System.out.println(otherVehicle.numberOfWheels); //error here!
  }
}

所以,重要的不是this。我可以访问同一类的其他对象的受保护字段,但不能访问超类型对象的受保护字段,因为超类型的引用可以包含任何对象,Car(如Bike)和Car 的不必要子类型可以'不访问从Vehicle 继承的不同类型的受保护字段(它们只能被扩展类及其子类型访问)。

【讨论】:

  • 能否详细说明“只能访问自己受保护的实例字段,不能访问同类其他实例的字段”。部分?我还更新了 OP 代码以显示派生类可以访问自己的字段以及派生类型的其他实例的字段(请查看 System.out.println(c.next); 部分)。
  • 换句话说,protected 成员是从 Derived 类的引用访问的,但不能从 Parent 类的引用访问(这是有道理的,因为这样的引用可以包含其他类型的实例我们的派生类,所以我们不应该访问它)。
  • @Pshemo 我错了——我已经更新了答案
猜你喜欢
  • 2014-11-26
  • 2019-10-06
  • 2018-11-23
  • 2015-05-09
  • 2011-06-22
  • 2017-01-01
  • 2018-02-11
  • 1970-01-01
相关资源
最近更新 更多