Can we create an instance of an interface in Java?

Ninja picture Ninja · Jan 3, 2011 · Viewed 195.3k times · Source

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?

Answer

Chad La Guardia picture Chad La Guardia · Jan 3, 2011

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.