据我了解,私有(private)字段只能在定义它们的类中访问。
我有一个基本的单链表代码:
public class LinkedList {
private class Node {
private String data;
private Node next;
private Node(String data, Node nextNode) {
this.data = data;
this.next = nextNode;
}
}
private Node head;
public LinkedList(String data) {
// Create head node, set next node null
head = new Node(data, null);
}
public void add(String data){
Node currentNode = head;
while(currentNode.next != null){
currentNode = currentNode.next;
}
currentNode.next = new Node(data, null);
}
public void printList(){
Node currentNode = head;
System.out.println(currentNode.data);
while(currentNode.next != null){
currentNode = currentNode.next;
System.out.println(currentNode.data);
}
}
}
它似乎运行和工作得很好,但我想弄清楚为什么我可以在类 LinkedList 的函数中访问类 Node 的“数据”和“下一个”字段。
除此之外,嵌套类是否与使用“extends”关键字定义的子类相同?
干杯,感谢您的帮助。
编辑:只是添加到这个问题上,在链接列表的其他实现中,我看到人们为节点和列表定义了两个单独的类。节点是链表的嵌套类对我来说更有意义。如果这不完全正确,请告诉我...
最佳答案
but I am trying to figure out why I can access the 'data' and 'next' fields of class Node in my functions in class LinkedList.
因为 Java Language Specification says so
[...] 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.
在您的案例中,顶级类是 LinkedList
。 Node
类是 LinkedList
的成员。因此,它(LinkedList
能够访问它的任何部分(Node
)是有意义的。
Adding onto this, is a nested class the same thing as a subclass defined with the 'extends' keyword?
没有。有关嵌套类的详细信息,请参阅 Java tutorials . extends
关键字用于继承。查看corresponding Java tutorial .
It made more sense to me for node to be a nested class of linkedlist. If this is not entirely correct please let me know...
不,你做的很好。使用您的 LinkedList
类的人对其实现方式不感兴趣,只要它遵循数据结构或规范的规则即可。您的 Node
类被嵌套并且 private
隐藏了这些细节。这被称为 information hiding和 encapsulation , 这被认为是好的做法。
请注意,您的嵌套类也被视为内部类。您也可以在前面的链接中阅读相关内容。
关于Java - 一个类可以访问其嵌套类的私有(private)字段吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21492334/