有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么子类看不到受保护字段?

我有一门课:

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
    }
}

为什么?


共 (1) 个答案

  1. # 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继承的受保护字段(它们仅可由扩展类及其子类型访问)