What happens to protected method of a super class in base class in Java?

前端 未结 1 1685
死守一世寂寞
死守一世寂寞 2021-01-20 16:55

I have a A class in package1 and B is in package2 which inherits A. A contains method m1<

1条回答
  •  逝去的感伤
    2021-01-20 17:26

    From JLS 6.6.2. Details on protected Access

    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.

    Let C be the class in which a protected member is declared. Access is permitted only within the body of a subclass S of C.

    Means The protected modifier specifies that the member can only be accessed within its own package (as with package-private) and, in addition, by a subclass of its class in another package.

    From Java Doc Controlling Access to Members of a Class
    enter image description here


    So you can access method m1 from class B even its not on same package because it subclass of A.
    But you can't access method m1 from class C because neither its in same package as A nor its subclass of A.

    So for accessing this method you can make method m1 public or move your class C into same package as class A

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