我有一个类:
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
}
}
为什么?
似乎如果子类在不同的包中,那么方法只能访问自己 protected 实例字段,而不能访问同一类的其他实例的字段。因此 this.last
和 this.next
可以工作,因为它们访问 this
对象的字段,但是 this.last.next
和 this.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
。我可以访问同一类的其他对象的 protected 字段,但不能访问父类(super class)型对象的 protected 字段,因为父类(super class)型的引用可以包含任何对象,而不是 Car
的必要子类型(如 Bike
) 和 Car
无法访问由 Vehicle
的不同类型继承的 protected 字段(它们只能被扩展类及其子类型访问)。