In the code above we have an interface called ExampleInterface that has just one method called interfaceMethod. And, we have another class called ExampleClass that just has one method called exampleMethod that accepts an object of type ExampleInterface (which is an interface) as an argument.

The question here – which we highlighted in red above – is if we want to call the exampleMethod method from another class, how do we invoke that method without an object that has the same type as the interface ExampleInterface?

Well, one obvious option is to create a new, separate class that implements the interface, so something like this:

Example of using an Argument Defined Anonymous Inner Class

But, as you probably guessed by the title of this article, another option is to use an Argument Defined Anonymous Inner Class instead. How does that work? Well, it’s quite simple – we just define the anonymous inner class directly inside the argument. You read that correctly – we are essentially defining and instantiating a class right inside an argument. Here is what the syntax for an argument defined anonymous inner class looks like, building on our previous example:

How does an Argument Defined Anonymous Inner Class work?

In the example code above, we create an instance of a class that implements the ExampleInterface interface, and we override the interfaceMethod as well. And, we do all of this inside an argument to a method! Amazing right? You might be confused, so let’s talk about this some more.

The key thing that you must understand is that we are creating both an implementation and an instance of a class that implements the ExampleInterface interface. Note that we are NOT instantiating the interface directly, even though the code may appear to be doing that – we are actually defining a class with no name (which is why it is called ANONYMOUS) that also implements the ExampleInterface interface. And then we create an instance of this class.