Java 中可以为接口创建对象吗?


不,您不能实例化接口。通常,它包含抽象方法(除了 Java8 中引入的默认方法和静态方法),这些方法是不完整的。

如果您仍然尝试实例化接口,则会生成编译时错误,提示“MyInterface 是抽象的;无法实例化”。

在以下示例中,我们有一个名为 MyInterface 的接口和一个名为 InterfaceExample 的类。

在接口中,我们有一个整数字段(公共、静态和最终)num 和抽象方法 demo()

从类中,我们尝试 - 创建接口的对象并打印 num 值。

示例

 在线演示

interface MyInterface{
   public static final int num = 30;
   public abstract void demo();
}
public class InterfaceExample implements MyInterface {
   public void demo() {
      System.out.println("This is the implementation of the demo method");
   }
   public static void main(String args[]) {
      MyInterface interfaceObject = new MyInterface();
      System.out.println(interfaceObject.num);
   }
}

编译时错误

编译上述程序时,会生成以下错误

输出

InterfaceExample.java:13: error: MyInterface is abstract; cannot be instantiated
   MyInterface interfaceObject = new MyInterface();
^
1 error

要访问接口的成员,您需要实现它并为其所有抽象方法提供实现。

示例

 在线演示

interface MyInterface{
   public int num = 30;
   public void demo();
}
public class InterfaceExample implements MyInterface {
   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();
      System.out.println(MyInterface.num);
   }
}

输出

This is the implementation of the demo method
30

更新于: 2020-06-29

16K+ 浏览量

启动您的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.