Help to understand the issue with protected method

前端 未结 6 1162
野的像风
野的像风 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:21

    I am almost certain that the question meant:

    "any instance of Y may call the abbey() method of any other instance of X" (not Y).

    In that case it will indeed fail. To borrow the example from another answer above, the following:

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

    will fail to compile.

    The Java Language Specification explains why here: http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.6.2

    6.6.2.1 Access to a protected Member

    Let C be the class in which a protected member m is declared. Access is permitted only within the body of a subclass S of C. In addition, if Id denotes an instance field or instance method, then: If the access is by a qualified name Q.Id, where Q is an ExpressionName, then the access is permitted if and only if the type of the expression Q is S or a subclass of S. If the access is by a field access expression E.Id, where E is a Primary expression, or by a method invocation expression E.Id(. . .), where E is a Primary expression, then the access is permitted if and only if the type of E is S or a subclass of S. (emphasis mine).

提交回复
热议问题