Re: Why does compiler only look at public methods of superclasses
of...?
failure_to@yahoo.co.uk wrote:
[...]
I'm actually reading "Java, the complete reference" by Herbert
Schildt. [...]
I'm not familiar with this book. However, at least two of
this author's other books on programming languages are said to
be somewhat less than perfectly accurate. There's a Wikipedia
article about Mr. Schildt, and some of the links it provides
make for interesting if disheartening reading.
A protected method is accessible from subclasses anywhere, *and*
throughout its own package, whether in subclasses or not.
If I'm not mistaken, protected method can be accessed from subclasses
anywhere, but these subclasses ( assuming they are in another
package ) can only call these protected methods on objects of the same
type as calling subclasses themselves? Thus:
class A{ protected void a(){...} }
class B extends A { // class B is in another package
public static void main( string[] args ){
B b = new B();
b.a(); // allowed
A a1 = new A();
a1.a(); // not allowed
}
}
Now B class( either inside class B static methods or inside B class
objects ) can only call method a() on objects of class B, but not on
objects of class A?!
Right. B's code is also unable to call method a() on
objects of some other class C that also extends A. Roughly
speaking, protected access must "go through channels" by
travelling up the inheritance hierarchy. The reasons for
this may become clearer if you ponder some of the ways that
protected is used: For example, look at the protected member
modCount in java.util.AbstractList, and consider how it is
used by subclasses like java.util.ArrayList.
2)
I apologize for asking another question, but still ...
I noticed that objects of same class can call each others private
methods and members:
[...]
So basically there is no way for object to hide its private members
from other objects of same type?
Right. Accessibility follows the organization of the
classes, not the organization of individual class instances.
If you don't want two instances of your class to peek at each
other's private members, just refrain from writing code that
peeks! The code is inside your class and under your control;
you can make your own rules about what is and isn't done.
--
Eric Sosman
esosman@ieee-dot-org.invalid