![](/img/trans.png)
[英]Why can’t this static inner class call a non-static method on its outer class?
[英]Why can we use 'new' keyword to get reference of a static inner class within a non-static outer class?
从下面的代码中可以看到,我们编写了RemoveDups_1.LinkedList linkedList = new RemoveDups_1.LinkedList();
在非静态类RemoveDups_1中获取静态类LinkedList的实例。 由于这是一个静态类,为什么我们需要使用new关键字来获取LinkedList
类的实例?
import java.util.*;
public class RemoveDups_1{
public static class LinkedList{
static int i = 5;
class Node{
int data;
Node next;
public Node(int data){
this.data = data;
}
}
Node head;
public void appendToTail(int data){
if(head == null){
head = new Node(data);
}
else{
Node node_to_append = new Node(data);
Node node = head;
while(node.next != null){
node = node.next;
}
node.next = node_to_append;
}
}
}
public static void main(String[] args){
RemoveDups_1 removeDups_1 = new RemoveDups_1();
RemoveDups_1.LinkedList linkedList = new RemoveDups_1.LinkedList();
RemoveDups_1.LinkedList.Node node;
node = linkedList.new Node(3);
System.out.println(RemoveDups_1.LinkedList.i);
}
}
LinkedList是嵌套类,您需要将其静态化才能实例化它,而无需创建其外部类的实例
“为什么我们需要使用new
关键字来获取LinkedList类的实例?”
因为这是您为类的实例分配内存的方式,而不管它是顶级类还是嵌套类(静态或内部)。 静态嵌套类成员和内部类成员之间的区别在于,前者不与外部类的实例相关联,而后者与外部类的实例相关联。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.