在 Java 中实例化接口

编程入门 行业动态 更新时间:2024-10-24 02:24:55
本文介绍了在 Java 中实例化接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有这个界面:

public interface Animal { void Eat(String name); }

这里的代码实现了接口:

And this code here implements the interface:

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(); // <- this line baby2.Eat("Meat"); } }

我的问题是,为什么代码有效?接口不能被实例化.然而在这种情况下,接口被实例化(用注释标记).

My question is, why does the code work? An interface cannot be instantiated. Yet in this case, interface was instantiated (marked with the comment).

这里发生了什么?

推荐答案

不,它不是 - 你正在实例化一个 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:37:56,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1298288.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实例   接口   Java

发布评论

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

>www.elefans.com

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