Can we create an instance of an interface in Java? [duplicate]

拟墨画扇 提交于 2019-11-26 04:06:50

问题


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  

Is it correct here?


回答1:


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/




回答2:


You can never instantiate an interface in java. You can, however, refer to an object that implements an interface by the type of the interface. For example,

public interface A
{
}
public class B implements A
{
}

public static void main(String[] args)
{
    A test = new B();
    //A test = new A(); // wont compile
}

What you did above was create an Anonymous class that implements the interface. You are creating an Anonymous object, not an object of type interface Test.




回答3:


Normaly, you can create a reference for an interface. But you cant create an instance for interface.




回答4:


Short answer...yes. You can use an anonymous class when you initialize a variable. Take a look at this




回答5:


No in my opinion , you can create a reference variable of an interface but you can not create an instance of an interface just like an abstract class.




回答6:


Yes it is correct. you can do it with an inner class.




回答7:


Yes we can, "Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name"->>Java Doc



来源:https://stackoverflow.com/questions/4587392/can-we-create-an-instance-of-an-interface-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!