Help to understand the issue with protected method
Posted
by zeroed
on Stack Overflow
See other posts from Stack Overflow
or by zeroed
Published on 2010-02-11T13:13:59Z
Indexed on
2010/03/09
3:36 UTC
Read the original article
Hit count: 426
I'm reading Sybex Complete Java 2 Certification Study Guide April 2005 (ISBN0782144195). This book is for java developers who wants to pass java certification.
After a chapter about access modifiers (along with other modifiers) I found the following question (#17):
True or false: If class Y extends class X, the two classes are in different packages, and class X has a protected method called abby(), then any instance of Y may call the abby() method of any other instance of Y.
This question confused me a little.
As far as I know you can call protected method on any variable of the same class (or subclasses). You cannot call it on variables, that higher in the hierarchy than you (e.g. interfaces that you implement).
For example, you cannot clone any object just because you inherit it.
But the questions says nothing about variable type, only about instance type.
I was confused a little and answered "true".
The answer in the book is
False. An object that inherits a protected method from a superclass in a different package may call that method on itself but not on other instances of the same class.
There is nothing here about variable type, only about instance type.
This is very strange, I do not understand it.
Can anybody explain what is going on here?
© Stack Overflow or respective owner