Provide an example of an anonymous class that implements an interface

If you already read our first article that included an example of an anonymous class in Java, then you know that the correct terminology is anonymous inner class and not anonymous class – there’s no such thing as anonymous inner classes without the “inner”.

Now that we clarified this point, let’s go through an example and a brief tutorial on an anonymous inner class that actually implements an interface. You can start out by taking a look at the code below.

Example of anonymous inner class implementing an interface

interface ProgrammerInterview  {

public void read();

}

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

An explanation of our example anonymous inner class implementing an interface

In the code above, we have an interface called ProgrammerInterview that has just one method declaration inside it. And, we have another class called Website.

Inside the Website class, the code in red is actually creating an instance of an anonymous inner class that implements the ProgrammerInterview interface. Read that sentence again, carefully, to make sure you understand it. The class that is being instantiated (where “p” is the instance variable) is anonymous because it has no name, and the anonymous class is actually implementing the ProgrammerInterview interface. This means that we are simultaneously creating an anonymous class that implements the ProgrammerInterview interface and also creating an instance of that anonymous class. Confusing right? Think about it for a little while until it is clear.

So, you are probably confused because you are used to seeing classes that implement interfaces using the “implements” keyword syntax so this code is what is familiar to you:

/*code to implement the ProgrammerInterview interface:*/
class SomeClass implements ProgrammerInterview //...

But, this is the only time in Java when you will see the syntax like what we showed above – where it looks like we are actually creating an instance of an interface class directly without even using the “implements” keyword. Remember that ProgrammerInterview is still an interface and not a normal class – even though we have the very odd-looking (for an interface) code below:

ProgrammerInterview p = new ProgrammerInterview () { 
//...
};

Hiring? Job Hunting? Post a JOB or your RESUME on our JOB BOARD >>

Subscribe to our newsletter for more free interview questions.

11 thoughts on “Anonymous Class Interface”