java接口可以创建对象_我们可以在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
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值