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() {
};
}
}
new 的是 无参构造,然后 又重写方法
这个我知道,我想知道的是,不是说接口不能创建对象吗,new出来的不都是对象吗,为什么没有报错,而且接口里面也提供了默认的无参构造?
他会帮你创建一个 匿名类,使用匿名类的形式,加上你重写的方法,再创建一个对象
创建的是子对象
new 的不是接口 是接口的匿名实现类
匿名内部类
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.