wood burning stoves
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
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "about package" Watch "about package" New topic

about package

nrshoo Lau

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?
Kathy Sierra
Cowgirl and Author

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

Joined: Dec 15, 2003
Posts: 2
thanks a lot.
it really helps.
I agree. Here's the link: http://aspose.com/file-tools
subject: about package
jQuery in Action, 3rd edition