我们可以在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
热门推荐
6 保研的祝福语简短
10 年轻20岁祝福语简短
11 朋友结婚祝福语信息简短
12 女孩婚礼贺卡祝福语简短
13 30段点歌简短祝福语
14 虎年春节祝福语图文简短
15 写给后妈祝福语大全简短
16 简短回复生日祝福语
17 校长送毕业祝福语简短
18 毕业立体贺卡祝福语简短