Access modifiers inside a private static nested class in Java

别来无恙 提交于 2019-12-09 03:04:50

问题


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 with no effect on my application.

public class MyList<T>{
    private static class Node{ // List node
        private Object item;
        private Node next;
        private Node prev;

        private Node(Node next){
            this.next = next;
        }

        private static Node doStuff(){}
    }
}

回答1:


Two kinds of nested classes: 1. Static (nested class) and 2. Non-static (also called inner class)

Now, the Outer class, MyList can access all the members of the inner class Node, but you actually use the access specifiers for the members of the class Node (nested class) when you want restrictions of some external class accessing it.

Interesting reads: Source1, Source2




回答2:


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

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.



来源:https://stackoverflow.com/questions/4075262/access-modifiers-inside-a-private-static-nested-class-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!