我们可以在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
热门推荐
1 泰迪狗狗如何训练
3 狗狗训练图
5 狗狗训练方法
6 训练狗狗不咬人
8 敏捷训练狗狗
10 训练狗狗吃饭
11 泰迪狗狗训练
12 狗狗从多大开始训练
13 狗狗训练学校费用
14 怎么去训练狗狗
15 狗狗训练狗狗
16 狗狗训练教程
17 训练狗狗装死
18 泰迪狗狗的训练方法