posted 20 years ago
Howdy,
If I understand the question correctly:
- How come a protected member from a superclass cannot be accessed by making an instance of that superclass from within the subclass?
For example:
class B extends A { }
class A {
protected int x;
}
If A and B are in DIFFERENT packages, then how come you can't say:
class B extends A {
void go() {
A a = new A();
a.x = 3; // x is protected, so doesn't that mean its accessible from subclasses, even if they are outside the package? Isn't that the point of 'protected'?
}
}
The reason that this does NOT work is because "protected" means "accessed through INHERITANCE, but NOT through access using a reference to an object of the superclass type."
In other words, class B HAS the "x" variable, but it does not have access to it by using a reference to a type A.
So it IS legal to say:
class B extends A {
void go() {
x = 3; // This is OK because B INHERITS the x.
}
}
The protected access level is different from all of the others in that it works ONLY for inheritance when the subclass is outside the package. (For subclasses INSIDE the package, it behaves just like 'default' access-- the subclass can refer to the protected variable through inheritance OR through accessing it using a reference of the superclass type.)
Does that help?
cheers,
kathy