Java 中私有静态嵌套类内的访问修饰符
我在 Java 中有一个“私有静态”嵌套类。此类中的字段和方法的访问修饰符有何意义?我已经尝试过公共和私人,对我的申请没有影响。
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(){}
}
}
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(){}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为它是一个嵌套类,所以
Node
中的所有内容都可以通过MyList
访问,无论访问修饰符如何;因为它是一个私有嵌套类,所以在Node
中首先声明的任何内容在MyList
之外都是不可见的。因此,访问修饰符可能很重要的一种情况是重写超类方法的方法(例如
toString()
)。您无法降低重写方法的可见性。toString()
必须始终声明为 public 以便该类能够编译。还应该注意的是,当外部类访问私有成员时,编译器会创建一个合成方法(我相信是包范围)。此合成方法仅在嵌套类的 .class 文件中可见。
Because it is a nested class, everything in
Node
can be accessed byMyList<T>
, regardless of access modifier; because it is a private nested class, nothing first declared inNode
will be visible outside ofMyList<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.
嵌套类有两种:1.静态(嵌套类)和2.非静态(也称为内部类)
现在,外部类
MyList
可以访问内部类的所有成员Node
,但当您希望限制某些外部类访问它时,您实际上对类Node
(嵌套类)的成员使用访问说明符。有趣的阅读:Source1、来源2
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 classNode
, but you actually use the access specifiers for the members of the classNode
(nested class) when you want restrictions of some external class accessing it.Interesting reads: Source1, Source2