This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Beginning Java and the fly likes about package Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "about package" Watch "about package" New topic
Author

about package

nrshoo Lau
Greenhorn

Joined: Dec 15, 2003
Posts: 2
class B extends A , and they are in different packages.
class A have one protected instance variable and one protected method.
in class B , A a=new A() .
Then , we will make errors by calling class A's members with a.
why? Have any proper cause?
thx~
Kathy Sierra
Cowgirl and Author
Ranch Hand

Joined: Oct 10, 2002
Posts: 1572
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
nrshoo Lau
Greenhorn

Joined: Dec 15, 2003
Posts: 2
thanks a lot.
it really helps.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: about package