• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

about package

 
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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~
 
Cowgirl and Author
Posts: 1589
5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
thanks a lot.
it really helps.
reply
    Bookmark Topic Watch Topic
  • New Topic