在Java中实例化接口

编程入门 行业动态 更新时间:2024-10-24 08:25:33
本文介绍了在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中实例化接口

本文发布于:2023-08-04 17:38:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1298291.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实例   接口   Java

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!