如果我们不能在 Java 中创建接口的实例,并且数组只是对象。那么,如何创建接口数组呢?
If we cannot create an instance of an interface in Java and arrays are nothing but Objects. Then, How is it possible to create Array of interface?
我在看一段代码,这让我很困惑。
interface Interviewer{
void conductInterview();
}
class Employees {
String name;
}
class HRexecutive extends Employees implements Interviewer{
String[] Specialization;
public void conductInterview(){
System.out.println("HR conduct interview");
}
}
public class paractise1 {
public static void main(String[] args) {
Interviewer interviewers [] = new Interviewer[1];
interviewers [0] = new HRexecutive();
}
}
上面的代码编译成功,但是我很困惑如何创建接口数组 "Interviewer" ,如果数组被视为 Java.
中的对象
接口只不过是断言 Object
具有某些方法/属性。此外,数组不存储对象本身,而是存储对对象的引用。这与使用 Interviewer
类型的变量存储 HRexecutive
的实例相同:Interviewer i = new HRexecutive();
。引用 i
驻留在堆栈内存中(至少,如果 i
是在方法中定义的),并持有对通过 new HRexecutive()
创建的实际实例的引用,该实例驻留在堆内存中.
如 中所述:如果数组元素的泛型类型为 instanceof Object
,则数组元素用 null
初始化。因此,当创建 Interviewer
的数组时,不会调用接口的构造函数。
数组是一个对象。它包含对接口类型对象的引用。这些引用最初是空的。创建数组时,任何地方都没有创建接口的实例。
我在看一段代码,这让我很困惑。
interface Interviewer{
void conductInterview();
}
class Employees {
String name;
}
class HRexecutive extends Employees implements Interviewer{
String[] Specialization;
public void conductInterview(){
System.out.println("HR conduct interview");
}
}
public class paractise1 {
public static void main(String[] args) {
Interviewer interviewers [] = new Interviewer[1];
interviewers [0] = new HRexecutive();
}
}
上面的代码编译成功,但是我很困惑如何创建接口数组 "Interviewer" ,如果数组被视为 Java.
中的对象接口只不过是断言 Object
具有某些方法/属性。此外,数组不存储对象本身,而是存储对对象的引用。这与使用 Interviewer
类型的变量存储 HRexecutive
的实例相同:Interviewer i = new HRexecutive();
。引用 i
驻留在堆栈内存中(至少,如果 i
是在方法中定义的),并持有对通过 new HRexecutive()
创建的实际实例的引用,该实例驻留在堆内存中.
如 instanceof Object
,则数组元素用 null
初始化。因此,当创建 Interviewer
的数组时,不会调用接口的构造函数。
数组是一个对象。它包含对接口类型对象的引用。这些引用最初是空的。创建数组时,任何地方都没有创建接口的实例。