Java程式:靜態內部類的使用示例


在這裡,我們將使用Java程式演示靜態內部類的用法。

在深入探討主題之前,讓我們先了解一下靜態內部類這個術語。

靜態內部類

內部類是在另一個類中定義的類。

靜態內部類是作為外部類靜態成員的巢狀類。

無需先例項化外部類即可使用其他靜態成員訪問它。

靜態巢狀類無法訪問外部類的例項變數和方法,這與Java中的靜態成員類似。

示例1

在下面的程式中,演示了靜態內部類訪問外部類靜態成員的能力,而無需建立外部類的例項。

// Java Program to demonstrate the Usage of Static Inner Class
// Beginning of Outer class
public class Tutorials_point1 {  
    // Display message of inner class
    static String s = "Have a great year ";
    // Beginning of Static Inner Class
    static class InnerClass {
        // Static Inner Class Method
        public void show(){
            // Show the message of inner class
            System.out.println("Happy New Year " + s);
        }
    }
    // Beginning of the Main method
    public static void main(String[] args){
        // Creation of an instance of the static inner class
        InnerClass instance = new InnerClass();
        // invoking the show() method
        // by the instance variable of inner class
        instance.show();
    }
}

輸出

Happy New Year Have a great year 

在上面的程式中,定義了一個名為"Tutorials_point1"的外部類,其中包含一個靜態字串變數"s"。它還包含一個名為"InnerClass"的靜態內部類,該類具有一個名為"show()"的方法,該方法使用外部類的靜態字串變數顯示訊息。

在主方法中,建立靜態內部類的例項,並在該例項上呼叫"show()"方法,該方法顯示訊息“新年快樂”以及靜態字串變數“s”的值。

示例2

在下面的程式中,演示了無需先建立外部類的例項即可建立靜態內部類例項的能力。建立靜態內部類例項的語法與建立非靜態內部類例項的語法不同。

// Java Program to demonstrate the Usage of Static Inner Class
// Beginning of Outer class
public class Tutorials_point2 {  
    // Static string message
    static String s = "Have a great year ";  
    // Beginning of Static Inner Class
    static class InnerClass {  
        // Static Inner Class Method
        public void show() {
            // Display message in inner class
            System.out.println("Happy New Year " + s);
        }
    }  
    //beginning of Main method
    public static void main(String[] args) {
        // Creation of an instance of the outer class
        Tutorials_point2.InnerClass instance = new Tutorials_point2.InnerClass();  
        // invoking method of static inner class via
        // the instance variable of outer class
        instance.show();
    }
} 

輸出

Happy New Year Have a great year 

在程式中,建立了一個名為"Tutorials_point2"的外部類,其中包含一個靜態字串變數"s"。它還包含一個名為"InnerClass"的靜態內部類,該類具有一個名為"show()"的方法,該方法使用外部類的靜態字串變數顯示訊息。

在主方法中,建立靜態內部類的例項。然後在該例項上呼叫"show()"方法,該方法顯示訊息“新年快樂”以及靜態字串變數“s”的值。

本文闡述瞭如何在Java中使用靜態內部類。文章首先討論了靜態內部類的概念。此外,還展示了兩個實現,以便更清晰地瞭解該主題。

更新於:2023年8月11日

瀏覽量:130

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告