我们可以在 Java 中创建接口的实例吗? [英] Can we create an instance of an interface in Java?

查看:43
本文介绍了我们可以在 Java 中创建接口的实例吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 Java 中创建接口的实例?

Is it possible to create an instance of an interface in Java?

我在某处读到使用内部匿名类我们可以做到如下所示:

Somewhere I have read that using inner anonymous class we can do it as shown below:

interface Test {
    public void wish();
}

class Main {
    public static void main(String[] args) {
        Test t = new Test() {
            public void wish() {
                System.out.println("output: hello how r u");
            }
        };
        t.wish();
    }
}

cmd> javac Main.java
cmd> java Main
output: hello how r u

这里正确吗?

推荐答案

是的,你的例子是正确的.匿名类可以实现接口,这是我能想到的唯一一次你会看到一个类实现了一个没有实现"接口的类.关键词.在此处查看另一个代码示例:

Yes, your example is correct. Anonymous classes can implement interfaces, and that's the only time I can think of that you'll see a class implementing an interface without the "implements" keyword. Check out another code sample right here:

interface ProgrammerInterview {
    public void read();
}

class Website {
    ProgrammerInterview p = new ProgrammerInterview() {
        public void read() {
            System.out.println("interface ProgrammerInterview class implementer");
        }
    };
}

这很好用.取自此页面:

This works fine. Was taken from this page:

http://www.programmerinterview.com/index.php/java-questions/anonymous-class-interface/

这篇关于我们可以在 Java 中创建接口的实例吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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