Help to understand the issue with protected method

前端 未结 6 1233
野的像风
野的像风 2021-01-12 00:54

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.

6条回答
  •  青春惊慌失措
    2021-01-12 01:16

    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.

    "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".

    Let's write that down, as BalusC did, and add to Y a method which calls the abby() of any other instance of Y:

    package one;
    public class X {
        protected void abby() {
        }
    }
    
    package other;
    import one.X;
    public class Y extends X {
        public void callAbbyOf(Y anyOther) {
            anyOther.abby();
        }
    }
    

    It is possible for Y to call the abby() method of any instance of Y to which it has a reference. So the answer in the book is blatantly wrong. Java does not have instance-specific scopes (unlike for example Scala which has an instance-private scope).

    If we try to be merciful, maybe the question meant by saying "any other instance of Y" that can it access the method of any instance of Y which happens to be in memory - which is not possible, because Java does not have direct memory access. But in that case the question is so badly worded, that you could even answer: "False. You can not call methods on instances which are on a different JVM, or instances which have been garbage collected, or instances on a JVM which died one year ago etc."

提交回复
热议问题