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

java 8object oriented programmingprogramming

不可以,您无法实例化接口。通常,它包含抽象方法(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

相关文章