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

当接口在Java中可以仅具有静态方法时,为什么接口没有静态初始化块?

Java中的接口类似于类,但是它仅包含final和static的抽象方法和字段。

静态方法是使用静态关键字声明,它将与类一起被加载到存储器。您可以使用类名访问静态方法而无需实例化。

自Java8以来接口中的静态方法

从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;
}

因此,接口中不必包含静态块。

猜你喜欢