Java 中的接口可以有静态方法吗?


Java 中的接口类似于类,但它只包含抽象方法和域,这些域是最终域和静态域。

静态方法使用 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

更新时间:2020-06-29

7000+ 观看数

启动您的职业

完成课程进行认证

开始
广告
© . All rights reserved.