Can we instantiate an interface in Java?

Is it possible to instantiate an interface in Java?

Somewhere I read that using an internal anonymous class, we can do this 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 ru"); } }; t.wish(); } } cmd> javac Main.java cmd> java Main output: hello how ru 

Is it correct?

+58
java interface inner-classes instance anonymous-class
Jan 03 2018-11-11T00:
source share
7 answers

Yes, your example is correct. Anonymous classes can implement interfaces, and that the only time I can think of it, you will see a class that implements an interface without the keyword "implements". Check out another code example:

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

It works great. Was taken from this page:

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

+34
May 01 '13 at 23:19
source share

You can never create an interface in java. However, you can refer to an object that implements an interface by type of 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 is to create an anonymous class that implements the interface. You are creating an anonymous object, not an object of type interface Test .

+77
Jan 03 '11 at 19:05
source share

Normal, you can create a link for the interface. But you cannot create an instance for the interface.

+4
Jan 03 '11 at 19:08
source share

The short answer is ... yes. You can use an anonymous class when initializing a variable. Take a look at this

+3
Jan 03 '11 at 19:05
source share

No, in my opinion, you can create an interface reference variable, but you cannot create an instance of an interface as an abstract class.

+3
Apr 25 '15 at 5:52
source share

Yes, it's right. you can do this with an inner class.

0
Jan 03 2018-11-11T00:
source share

Yes, we can: "Anonymous classes allow you to make your code more concise, they allow you to declare and instantiate a class at the same time. They are similar to local classes, except that they have no name" - → Java Doc

0
Dec 23 '14 at 19:38
source share