Java 中的接口可以有静态方法吗?
java 8object oriented programmingprogramming
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