Why interfaces don't have static initialization block when it can have static methods alone in java?

Java 8Object Oriented ProgrammingProgramming

An interface in Java is similar to class but, it contains only abstract methods and fields which are final and static.

A static method is declared using the static keyword and it will be loaded into the memory along with the class. You can access static methods using class name without instantiation.

Static methods in an interface since java8

Since Java8 you can have static methods in an interface (with body). You need to call them using the name of the interface, just like static methods of a class.

Example

In the following example, we are defining a static method in an interface and accessing it from a class implementing 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

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

Static blocks

A static block is a block of code with a static keyword. In general, these are used to initialize the static members. JVM executes static blocks before the main method at the time of 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 main method");
   }
}

Output

Hello this is a static block
This is main method

Static blocks in interfaces

Mainly, static blocks are used to initialize the class/static variables if you have not initialized them at the time of declaration.

In case of interfaces when you declare a field in it. It is mandatory to assign value to it else, a compile time error is generated.

Example

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

Compile time error

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

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

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

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

raja
Published on 05-Aug-2019 17:58:28
Advertisements