本文介绍了在Java中实例化接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个界面:
public interface Animal {
public void Eat(String name);
}
此代码实现了界面:
public class Dog implements Animal {
public void Eat(String food_name) {
System.out.printf(food_name);
}
public static void main(String args[]) {
Animal baby2 = new Dog(); //HERE!!!!!!!!!!!!!!!!!!!!!!
baby2.Eat("Meat");
}
}
我的问题是,为什么代码有效?无法实例化接口。然而在这种情况下,界面被实例化(标记为HERE !!!!!!!!!!!!!!)。
My question is, why does the code work? An interface cannot be instantiated. Yet in this case, interface was instantiated (marked with the comment "HERE!!!!!!!!!!!!!").
这里发生了什么?
推荐答案
不,不是 - 你正在实例化一个 Dog
,但由于 Dog
是 Animal
,您可以将变量声明为 Animal
。如果您尝试实例化接口 Animal
,它将是:
No it is not - you are instantiating a Dog
, but since a Dog
is an Animal
, you can declare the variable to be an Animal
. If you try to instantiate the interface Animal
it would be:
Animal baby2 = new Animal();
试试看,并惊恐地看着编译器尖叫:)
Try that, and watch the compiler scream in horror:)
这篇关于在Java中实例化接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!