It seems that if the subclass is in a different package, then methods can only access their own protected instance fields, not those of other instances of the same class. Hence this.last
and this.next
work because they access the fields of this
object, but this.last.next
and this.next.last
will not work.
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
}
EDIT - I wasn't quite right. Thanks for the upvotes anyway :)
I tried an experiment. I have this class:
public class Vehicle {
protected int numberOfWheels;
}
And this one in a different package:
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!
}
}
So, it's not this
which is the important thing. I can access protected fields of other objects of the same class, but NOT protected fields of objects of the supertype, since reference of supertype can hold any object, not necessary subtype of Car
(like Bike
) and Car
can't access protected fields inherited by different type from Vehicle
(they are accessible only to extending class and its subtypes).