Access modifiers inside a private static nested class in Java

前端 未结 2 1746
清酒与你
清酒与你 2021-01-12 03:54

I have a \"private static\" nested class in Java. What is the significance of access modifiers for fields and methods inside this class? I\'ve tried both public and private

2条回答
  •  梦毁少年i
    2021-01-12 04:36

    Because it is a nested class, everything in Node can be accessed by MyList, regardless of access modifier; because it is a private nested class, nothing first declared in Node will be visible outside of MyList.

    So, the one case where the access modifier may matter are methods that override a superclass method(e.g. toString()). You can not reduce the visibility of an overridden method. toString() must always be declared public in order for the class to compile.

    It should also be noted that when private members are accessed by the outer class, the compiler creates a synthetic method (I believe of package scope). This synthetic method is only visible in the .class file of the nested class.

提交回复
热议问题