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

Por que a interface não tem um bloco de inicialização estático quando pode ter apenas métodos estáticos no Java?

em JavaInterfacessemelhantes às classes, mas que contêm apenas métodos e campos abstratos finais e estáticos.

Métodos estáticossão declarados com a palavra-chave static, que é carregada juntamente com a classe para a memória. Você pode acessar métodos estáticos usando o nome da classe sem a necessidade de instanciar.

desde Java8métodos estáticos em interfaces

Desde Java8Para começar, você pode usar métodos estáticos dentro da interface (com corpo). Você precisa usar o nome da interface para chamá-los, da mesma forma que os métodos estáticos de uma classe.

Example

Neste exemplo, definimos um método estático na interface e acessamos ele a partir da classe que implementa a 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 block of code using the static keyword. Usually, 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

Mainly, 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. It must be assigned a value, otherwise a compilation time error will be generated.

Example

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

Compilation time error

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

When you assign a value to a static final variable in an interface, this problem will be resolved.

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

Therefore, static blocks do not need to be included in the interface.

Você também pode gostar