Why do inner classes make private methods accessible?

前端 未结 4 802
难免孤独
难免孤独 2020-11-28 06:25

I don\'t understand why this compiles. f() and g() are visible from the inner classes, despite being private. Are they treated special specially because they are inner clas

4条回答
  •  萌比男神i
    2020-11-28 07:06

    As User 'A Dude' explained it in the comments of the accepted answer:

    It compiles, because it is required to be working in that way by the language specifation, ie. the Java Lang Spec says so:

    6.6.1 Determining Accessibility (at least since JLS6)

    "Otherwise, if the member or constructor is declared private, then access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor."

    I.e. the "access-scope" of a private member is: everywhere within the lexical boundaries of the top-level class body.

    That means: all private members that are defined within the class-body of the outermost class can be accessed from everywhere else in this class-body.

    For instance the private method of an inner class can be accessed from methods of the outer class or from any method of another inner class of the outer class.

提交回复
热议问题