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

查看:293
本文介绍了我们可以在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  

这里是否正确?

推荐答案

是的,你的例子是正确的。匿名类可以实现接口,这是我唯一能想到的,你会看到一个实现没有implements关键字的接口的类。在这里查看另一个代码示例:

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天全站免登陆