首页 新闻 会员 周边

java接口不能创建对象,为什么又可以new呢,头痛啊,,,,求解答

0
悬赏园豆:20 [待解决问题]

java接口不能创建对象,为什么又可以new呢,头痛啊,,,,求解答
package interfacedemo;
//接口不能创建对象

//接口1
interface Question {
String name = "SLEEP";

void sleep();

}

//接口2
interface Question2 {
}

class Test1 {
public static void main(String[] args) {
//创建接口1的对象
Question q = new Question() {
@Override
public void sleep() {
System.out.println("我要睡觉");
}
};
// 创建接口库二的对象
Question2 q2 = new Question2() {
};

}

}

恐龙串的主页 恐龙串 | 初学一级 | 园豆:183
提问于:2022-05-31 23:39
< >
分享
所有回答(7)
0

new 的是 无参构造,然后 又重写方法

不苦 | 园豆:20 (初学一级) | 2022-06-01 00:18

这个我知道,我想知道的是,不是说接口不能创建对象吗,new出来的不都是对象吗,为什么没有报错,而且接口里面也提供了默认的无参构造?

支持(0) 反对(0) 恐龙串 | 园豆:183 (初学一级) | 2022-06-01 00:42
0

他会帮你创建一个 匿名类,使用匿名类的形式,加上你重写的方法,再创建一个对象

god-smile | 园豆:564 (小虾三级) | 2022-06-01 11:25
0

new interface 相当于创建了一个实现该接口的匿名类,一般用在局部方法里面

https://docstore.mik.ua/orelly/java-ent/jnut/ch03_12.htm

huiyuanai709 | 园豆:487 (菜鸟二级) | 2022-06-01 11:34
0

创建的是子对象

明日小路 | 园豆:466 (菜鸟二级) | 2022-06-01 16:20
0

new 的不是接口 是接口的匿名实现类

蓝羽code | 园豆:313 (菜鸟二级) | 2022-06-01 17:26
0

匿名内部类

iRyz | 园豆:210 (菜鸟二级) | 2022-06-02 17:37
0

Java is the most generally involved programming language in the ongoing IT industry. One significant justification behind the huge number of novices and experts in the field of writing computer programs is the professional potential that Java information accompanies. This article is committed to a similar reason. Here is a finished aide on the best way to assist you with breaking the most often asked Java Interview inquiries within Job Oriented Java Certification Course in Pune.

surbhinahta | 园豆:216 (菜鸟二级) | 2022-06-06 13:44
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册