logo

Javaの静的クラス

Java では、クラスを別のクラス内で定義できます。これらはと呼ばれます ネストされたクラス 。ほとんどの開発者はクラスを静的にできることを認識しており、今後は Java で一部のクラスを静的にできるようになります。 Java サポート 静的インスタンス変数 静的メソッド 静的ブロック 、静的クラス。ネストされたクラスが定義されているクラスは、 アウタークラス 。最上位クラスとは異なり、 ネストされたクラスは静的にすることができます 。非静的ネストされたクラスは、次のようにも呼ばれます。 内部クラス

注記: Java では最上位クラスを静的にすることはできません。静的クラスを作成するには、ネストされたクラスを作成してからそれを静的にする必要があります。



内部クラスのインスタンスは、外部クラスのインスタンスがなければ作成できません。したがって、内部クラスのインスタンスは、外部クラスのインスタンスへの参照を使用せずに、その外部クラスのすべてのメンバーにアクセスできます。このため、内部クラスはプログラムをシンプルかつ簡潔にするのに役立ちます。

文字列.形式

覚えて: 静的クラスではオブジェクトを簡単に作成できます。

静的入れ子クラスと非静的入れ子クラスの違い

以下は、静的ネストされたクラスと内部クラスの主な違いです。



  1. 静的ネストされたクラスは、その外部クラスをインスタンス化せずにインスタンス化できます。
  2. 内部クラスは、外部クラスの静的メンバーと非静的メンバーの両方にアクセスできます。静的クラスは、外部クラスの静的メンバーにのみアクセスできます。

静的および非静的ネストされたクラス

以下は、上記のトピックの実装です。

ジャワ






// Java program to Demonstrate How to> // Implement Static and Non-static Classes> // Class 1> // Helper class> class> OuterClass {> >// Input string> >private> static> String msg =>'GeeksForGeeks'>;> >// Static nested class> >public> static> class> NestedStaticClass {> >// Only static members of Outer class> >// is directly accessible in nested> >// static class> >public> void> printMessage()> >{> >// Try making 'message' a non-static> >// variable, there will be compiler error> >System.out.println(> >'Message from nested static class: '> + msg);> >}> >}> >// Non-static nested class -> >// also called Inner class> >public> class> InnerClass {> >// Both static and non-static members> >// of Outer class are accessible in> >// this Inner class> >public> void> display()> >{> >// Print statement whenever this method is> >// called> >System.out.println(> >'Message from non-static nested class: '> >+ msg);> >}> >}> }> // Class 2> // Main class> class> GFG {> >// Main driver method> >public> static> void> main(String args[])> >{> >// Creating instance of nested Static class> >// inside main() method> >OuterClass.NestedStaticClass printer> >=>new> OuterClass.NestedStaticClass();> >// Calling non-static method of nested> >// static class> >printer.printMessage();> >// Note: In order to create instance of Inner class> >// we need an Outer class instance> >// Creating Outer class instance for creating> >// non-static nested class> >OuterClass outer =>new> OuterClass();> >OuterClass.InnerClass inner> >= outer.>new> InnerClass();> >// Calling non-static method of Inner class> >inner.display();> >// We can also combine above steps in one> >// step to create instance of Inner class> >OuterClass.InnerClass innerObject> >=>new> OuterClass().>new> InnerClass();> >// Similarly calling inner class defined method> >innerObject.display();> >}> }>

>

>

出力

Message from nested static class: GeeksForGeeks Message from non-static nested class: GeeksForGeeks Message from non-static nested class: GeeksForGeeks>