作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我试图通过Java解决LinkedList的问题,但是我发现了静态内部类的概念,我被困在这里了!
我的代码正在运行,但无法理解如何创建静态类对象
public class findNthNodeInLL {
static class Node {
int data;
Node next;
Node(int data) {
this.data = data;
next = null;
}
}
int findNthNode(Node head, int count) {
int pos = 0;
Node ptr = head;
while(ptr != null && pos != count) {
pos++;
ptr = ptr.next;
}
return ptr.data;
}
public static void main(String[] args) {
findNthNodeInLL ll = new findNthNodeInLL();
Node head = new Node(1);
head.next = new Node(2);
head.next.next = new Node(3);
head.next.next.next = new Node(4);
head.next.next.next.next = new Node(5);
System.out.println(ll.findNthNode(head,3));
}
}
内部类对象(即头)正在创建,没有外部类的任何引用。甚至在没有任何外部类引用的情况下调用构造函数并创建内存。
这里的实际场景是什么?怎么了?为什么我们不为内部类构造函数或对象使用任何外部类引用?
也许我错过了一些东西。请帮我理解这里的场景。
最佳答案
您在外部类本身内部使用静态类,因此您不需要放置封闭的类名称。静态嵌套类在行为上与任何静态字段类似。
但是,如果您想在外部类之外实例化静态嵌套类,则必须在其定义中放置封闭类名称或使用对外部类的引用。
例如:
public class Main {
static class NodeInside {
int data;
NodeX.Node next;
NodeInside(int data) {
this.data = data;
next = null;
}
}
public static void main(String[] args) {
NodeX ll = new NodeX();
NodeX.Node head = new NodeX.Node(1); // need to put the enclosing class name
NodeInside nodeInside = new NodeInside(1); // no need to put the enclosing class
}
}
class NodeX{
static class Node {
int data;
Node next;
Node(int data) {
this.data = data;
next = null;
}
}
}
关于java - 静态类Object如何在没有引用的情况下创建?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54759656/
我是一名优秀的程序员,十分优秀!