在 Java 中实例化接口 [英] Instantiating interfaces in Java

查看:29
本文介绍了在 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 中实例化接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆