亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

靜態類 Object 是如何在沒有引用的情況下創建的?

靜態類 Object 是如何在沒有引用的情況下創建的?

一只甜甜圈 2022-06-23 20:25:15
我試圖通過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));}}內部類對象(即頭部)在沒有任何外部類引用的情況下被創建。甚至正在調用構造函數并且正在創建內存而沒有任何外部類引用。這里的實際情況是什么?怎么了?為什么我們不對內部類構造函數或對象使用任何外部類引用?也許我錯過了一些東西。請幫助我了解這里的情況。
查看完整描述

1 回答

?
慕后森

TA貢獻1802條經驗 獲得超5個贊

您在外部類本身內部使用靜態類,因此您不要放置封閉類名稱。靜態嵌套類在行為上類似于任何靜態字段。


但是如果要在外部類之外實例化靜態嵌套類,則必須在其定義上放置封閉類名稱或使用對外部類的引用。


例如 :


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;

    }

}

}


查看完整回答
反對 回復 2022-06-23
  • 1 回答
  • 0 關注
  • 85 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號