R.E.M. Web Development

Can you instantiate an interface in Java?

Can you instantiate an interface in Java? The answer is no, but you might see some code examples that cause you to scratch your head and question your understanding of the rule. Lets say we have this interface:

public interface MyInterface{
public void myMethod();
}

 

You can actually create an anonymous class that implements this interface like this:

MyInterface myInterface = new MyInterface(){
@Override
public void myMethod(){
//some code goes here...
}
};

 

When I was first learning Java this really confused me. But what's really going on is that you are creating an anonymous inner class that implements the interface. And you can get away with instantiating it like this because you are providing the implementation to satisfy the contract of the interface. Note that the @Override annotation simply tells the compiler to make sure you are using the same signature as the method that is declared in MyInterface.

This pattern is actually very common, and you'll see it a lot in GUI programming, and you'll also see it in Android quite a bit.

I got confused because I did not see the 'implements' keyword anywhere. I would have guessed that the syntax for doing this would look something like this, but this goofy because it's not really an anonymous class:

MyInterface myInterface = new Blah implements MyInterface(){
public void myMethod(){
//some code goes here...
}
};

 

Note that anonymous inner classes can either extend a class OR can implement only one interface. Here's an example of an anonymous class that extends a class (notice that it does not include the 'extends' keyword):

BaseClass baseClass = new BaseClass(){
//code goes here...
};