English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Javaのインターフェースクラスと同様ですが、finalおよびstaticの抽象メソッドとフィールドのみを含みます。
甲静的メソッドのインターフェース内の静的メソッドは、静的キーワードを使用して宣言され、クラスとともにメモリにロードされます。クラス名を使用して静的メソッドにアクセスすることができ、インスタンス化することなくアクセスできます。
Java8最初に、インターフェース(主体を持つ)内で静的メソッドを使用できます。これらは、クラスの静的メソッドのように、インターフェースの名前を使用して呼び出されます。
以下の例では、インターフェース内で静的メソッドを定義し、そのインターフェースを実装するクラスからアクセスします。
interface MyInterface{ public void demo(); public static void display() { System.out.println("This is a static method"); } } public class InterfaceExample{ public void demo() { System.out.println("This is the implementation of the demo method"); } public static void main(String args[]) { InterfaceExample obj = new InterfaceExample(); obj.demo(); MyInterface.display(); } }
出力結果
This is the implementation of the demo method This is a static method
甲静的ブロックこれは静的キーワードを使用するコードのブロックです。通常、これらは静的メンバーの初期化に使用されます。JVMはクラスをロードする際にmainメソッドの前に静的ブロックを実行します。
public class MyClass { static{ System.out.println("Hello this is a static block"); } public static void main(String args[]){ System.out.println("This is main method"); } }
出力結果
Hello this is a static block This is main method
主に、宣言時に静的ブロックが初期化されていない場合、それらはクラスの初期化に使用されます/静的変数。
インターフェースでフィールドを宣言する場合、それに値を割り当てないとコンパイル時エラーが生成されます。
interface Test{ public abstract void demo(); public static final int num; }
Test.java:3: error: = expected public static final int num; ^ 1 error
インターフェースで静的最終変数に値を割り当てると、この問題が解決します。
interface Test{ public abstract void demo(); public static final int num = 400; }
したがって、インターフェースには静的ブロックを含めなくても良い。