Understanding java's protected modifier

后端 未结 6 2272
感情败类
感情败类 2020-11-22 06:45

I have a class called A in package1 and another class called C in package2. Class C extends class A.

A has an instance variable which is declared like this:

<
6条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-22 07:37

    What's going on here?

    You've misunderstood the meaning of protected. You can access the protected members declared in A from within C, but only for instances of C or subclasses of C. See section 6.6.2 of the JLS for details of protected access. In particular:

    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.

    In addition, if Id denotes an instance field or instance method, then:

    • [...]

    • 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.)

    So this code would be fine:

    C c = new C();
    System.out.println(c.publicInt);
    System.out.println(c.protectedInt);
    

提交回复
热议问题