简体   繁体   English

如何在没有引用的情况下创建静态类Object?

[英]How static class Object is created without reference?

I was trying to solve problems of LinkedList through Java, But I found out the concept of static inner class and I am stuck here! 我试图通过Java解决LinkedList的问题,但是我发现了静态内部类的概念,因此我被困在这里!

My code is working, But could not understand how the static class object is being Created 我的代码正常工作,但无法理解如何创建静态类对象

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));
}
}

The Inner class Object ie head is being created without any reference of the outer class. 内部类对象(即head)的创建没有外部类的任何引用。 Even the constructor is being called and the memory is being created without any outer class reference. 甚至在没有任何外部类引用的情况下,甚至调用了构造函数并创建了内存。

What is the actual scenario over here? 这里的实际情况是什么? What is happening? 怎么了? Why are we not using any outer class reference for the inner class constructor or object? 为什么我们不对内部类构造函数或对象使用任何外部类引用?

Maybe I am missing something. 也许我缺少了一些东西。 Please help me understand the scenario over here. 请帮助我了解这里的情况。

You are using the static class inside the outer class itself so You don't to put the enclosing class name. 您在外部类本身内部使用了静态类,因此不要放入封闭的类名。 A static nested class is behaviorally like any over static fields. 静态嵌套类的行为类似于任何静态字段。

But If you want to instantiate the static nested class outside the outer class, you have to put the enclosing class name or use reference to the outer class on its definition. 但是,如果要在外部类外部实例化静态嵌套类,则必须在其定义上放置封闭的类名称或使用对外部类的引用。

For example : 例如 :

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;
    }
}
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM