Java: protected access across packages

后端 未结 4 1613
我在风中等你
我在风中等你 2020-12-14 11:20

I would like to understand what\'s happening in the example below (where a protected member is being accessed from outside the package through a subclass).

I know fo

相关标签:
4条回答
  • 2020-12-14 11:41

    take a look on this picture from : http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html

    enter image description here

    its clear that protected member of class can be accessed via subclass.

    0 讨论(0)
  • 2020-12-14 11:42

    It is working in the first case because it is being called from the same class even the method is being accessed through a reference. You could even call a private method of ExtendsprotectedClass through a reference in the same main method.

    0 讨论(0)
  • 2020-12-14 11:44

    I believe you've answered your own question; UsesExtendedClass does not inherit from ProtectedClass, and -- by definition -- "protected" members are accessible only in the class in which they are declared / defined or in a class that inherits from the one in which they are declared or defined.

    0 讨论(0)
  • 2020-12-14 12:06

    Code within the ExtendsprotectedClass class is allowed to access protected members of ProtectedClass via a reference of type ExtendsprotectedClass. From the JLS section 6.6.2:

    A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.

    and

    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. [...]

    UsesExtendedClass isn't reponsible for the implementation of ExtendsprotectedClass, hence the final call fails.

    EDIT: The reasoning behind this is that protected access is designed to help subclasses implement the functionality they need, giving more access to the internals of the superclass than would normally be available. If that were available to all code, it would be pretty close to making the method public. Basically, the subclasses are trusted not to break encapsulation; they're given more capabilities within objects of their own type. The public API shouldn't expose those details, but the protected API can just for the purposes of giving subclasses more opportunities.

    0 讨论(0)
提交回复
热议问题