English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Why does an interface not have a static initialization block when it can only have static methods in Java?

in JavaInterfacesare similar to classes, but they only contain final and static abstract methods and fields.

Static methodsare declared using the static keyword, which is loaded into memory along with the class. You can access static methods using the class name without instantiating an object.

since Java8static methods in interfaces

From Java8Initially, you can use static methods in the interface (with a body). You need to use the interface name to call them, just like class static methods.

Example

In the following example, we define a static method in the interface and access it from a class that implements the interface.

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

Output Result

This is the implementation of the demo method
This is a static method

Static Block

Static BlockThis is a code block using the static keyword. Typically, these are used to initialize static members. The JVM executes static blocks before the main method during class loading.

public class MyClass {
   static{
      System.out.println("Hello this is a static block");
   }
   public static void main(String args[]){
      System.out.println("This is the main method");
   }
}

Output Result

Hello this is a static block
This is the main method

Static Blocks in Interfaces

Primarily, if the static block has not been initialized at the time of declaration, it will be used to initialize the class/Static Variables.

When declaring fields in an interface, you must assign a value to it, otherwise a compilation error will be generated.

Example

interface Test{
   public abstract void demo();
   public static final int num;
}

Compilation Error

Test.java:3: error: = expected
   public static final int num;
                              ^
1 error

This problem will be resolved when you assign a value to a static final variable in the interface.

interface Test{
   public abstract void demo();
   public static final int num = 400;
}

Therefore, it is not necessary to include static blocks in the interface.

You May Also Like