Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

about package

 
nrshoo Lau
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Rancher
Posts: 1589
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks a lot.
it really helps.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic