> > Eric gave you the right answer, but to clarify a bit...
>
[quoted text clipped - 4 lines]
>
> -- Lew
> and yesterday i come to know that i can only access protected
> members in different package with subclass reference. I can not access
> them with parent reference. Can anyone tell me why is this so?
I don't know what you mean by "subclass reference" and "parent
reference", but hopefully this will clarify things for you:
http://java.sun.com/docs/books/tutorial/java/javaOO/accesscontrol.html
- Oliver
> yesterday i come to know that i can only access protected
> members in different package with subclass reference. I can not access
> them with parent reference. Can anyone tell me why is this so?
You seem to be trying to use protected as if meant the same thing as
public. It means almost the same, but does have some minor uses.
Suppose classes X and Y both extend class Base, which has a protected
instance member p.
package b;
abstract class Base { protected int p; }
package x;
class X extends b.Base { ... }
package y;
class Y extends b.Base { ... }
The idea is that X can only access p of instances of type X. X should
not be able to access p in an instance of Y.
If a variable is declared to have type Base, then it's not explicit
which implementation class it is an instance of. Therefore, code in X
and Y should not be able to access its protected members.
Whenever you feel the need to declare something as protected, think a
bit harder about it until you change your mind. There are some instances
where it is genuinely useful, but they are quite rare.
Tom Hawtin
Lew - 14 Mar 2007 02:42 GMT
> to access its protected members.
Not only was this one of the clearest yet brief elucidations of a concept I
have read, but it used the correct "its" spelling.
> Whenever you feel the need to declare something as protected, think a
> bit harder about it until you change your mind. There are some instances
> where it is genuinely useful, but they are quite rare.
Maybe not "rare" as in "infrequent" so much as in "for very specific and
tightly constrained purposes". When used correctly, protected access is powerful.
I have used protected connection parameters in data access objects. I suppose
there was a better way, now that I am thinking about Tom's advice, but it was
convenient. Perhaps protected accessor methods instead.
More often than members, I declare protected methods for certain subclass
functionality from outside the base class package. Such methods usually occur
only in abstract classes, and usually are final. One example is a data access
object connection establishment method.
Statistically frequent or not, these are particular situations with specific
reasons to use protected access. Protected access is a tool for the design of
heritable classes, also something to do sparingly.
That fits in the meme set of "quite rare".
- Lew