Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 906
Ninja Avatar asked Jan 03 '11 19:01

Ninja


People also ask

Can you create an instance of an interface Java?

You cannot create instances of a Java interface by itself. You must always create an instance of some class that implements the interface, and reference that instance as an instance of the interface.

Is it possible to create an instance of interface?

You cannot create an instance of an interface , because an interface is basically an abstract class without the restriction against multiple inheritance. And an abstract class is missing parts of its implementation, or is explicitly marked as abstract to prohibit instantiation.

What happens when two interfaces are created with same name?

If a type implements two interfaces, and each interface define a method that has identical signature, then in effect there is only one method, and they are not distinguishable. If, say, the two methods have conflicting return types, then it will be a compilation error.

Can two interface have same method in Java?

If two interfaces contain a method with the same signature but different return types, then it is impossible to implement both the interface simultaneously. According to JLS (§8.4. 2) methods with same signature is not allowed in this case.


1 Answers

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.

like image 190
Chad La Guardia Avatar answered Sep 27 '22 20:09

Chad La Guardia