Java Anonymous Inner Class | Anonymous Class Java Example

There is this special type of class known as Java Anonymous Inner Class that are often used when people are too tired to think of a class name. Like that’s a thing right? Just kidding!

An anonymous inner class is used when you need to override a method of a class or an interface. Well, you might argue we can do that even by using a normal class, can’t we? Yes, you can. It is just that creating a Java anonymous inner class just saves you so much time and effort.

A man needs a name meme from GOT anonymous inner class Java

Like the other day I was working on Threads and I realized everybody preferred creating a Java anonymous inner class to using a separate class to call work. It was quite cool since you could declare and provide implementations then and there. It was so much less work that I decided to do this chapter to cover this entire topic.

How to Create a Java Anonymous Inner Class

It goes without saying that anonymous class doesn’t have a name. Did the moniker give it away?

Creating one is like a walk in the park. There are two ways you can use to do that:

  1. Using a Class
  2. Using an interface

Here’s the syntax you need to remember:

ClassName c = new ClassName() {

       public void methodtoOverride() {
               -----implementation-----
        }

};

Remember there is a “;” symbol at the end. Do not miss that or you will get a compile time error.

The method name is quite self-explanatory. The ClassName should be replaced by whatever class name your base class has, and whatever methods it has can be implemented inside the inner class we create.

Anonymous Class Java Example Using Class (Abstract)

Here an example would make your life better. Imagine there’s an abstract class named Fire which has an abstract method called burn():

abstract class Fire { 

                    abstract void burn(); 

}

Now we need to provide the implementation for burn() in our newly found Java Anonymous Inner Class:

Java Anonymous inner class example

Here, I have simply used sysout to display something in the method.

Eventually, I have called the method using the same reference we had created for our abstract class Fire. The reason we are not using “extends Fire” here is because Superpowers isn’t the derived class calling the Base class. It is done by our anonymous class in a hidden manner. We will see what’s going in really in a bit.

If you run the above you will get:

Nope

So what is happening in actuality?

When you are putting the following code:

Fire t = new Fire() {

     public void burn() {

                System.out.println("Nope");

}

What your compiler does is, create an anonymous class that extends Fire(). The burn() method’s implementation is expected since it has extended the abstract base class.  So you have to provide the implementation by declaring the method.

An object of the anonymous class is created and is assigned to the reference ‘t’.

So internally this is what is happening inside the JVM:

import java.io.PrintStream;

static class RandomAnonymousName$ extends Fire {

                 RandomAnonymousName$ () {

                 }

                 public void burn() {

                              System.out.println("Nope");

          }

}

So now it feels like a regular class doesn’t it?

Hope that clears the concept.

Anonymous Class Java Example Using Class (Abstract)

Now, this isn’t limited to just abstract classes, even if there is a concrete class you could make use of anonymous inner class to override its methods.

Learn about concrete class.

Let’s assume we have a concrete class named Fire.

public class Fire { 

              public void burn() { 
                            System.out.println("This is insane"); 
              } 
}

We will use the same code that we had used earlier to override the burn() method above:

Java Anonymous inner class example

Calling the method t.burn() will this time override the burn() method in our concrete class and print the following instead:

Nope

Anonymous Class Java Example Using Interface

We will now see how things work out when there is an interface involved:

The syntax here is the same, just replace the ClassName with the InterfaceName, that is all.

InterfaceName c = new InterfaceName() {

       public void methodToOverride() {
           -----implementation-----
        }

};

So now let’s put this in an example and see.

Suppose we have an interface called Water with a method name swish():

interface Water {

            void swish();  

}

Will use the same steps to refer our code the interface Water(). Will have to provide the implementation of the method swish():

Anonymous class using Interface in Java

If you run the above program you will get the following result:

Yep

The Compiler functioning is the same here except that the anonymous class that it creates in the background “implements” instead of extends.

Passing an Object of Anonymous Inner Class as an Argument

Now the question is: What else could you do with your anonymous inner class? We can use it as an argument too.

Whaaaaat?

Yes. The fact that we could pass an object of an Interface or Class in a method argument leaves that possibility open. Of course, you have to use the new keyword to create an instance of the Anonymous Inner Class.

Here’s the syntax you need to follow:

methodName(new ClassName() {

         public void methodtoOverride() {

               ------implementation------

       }

});

Pay attention to the way it closes. This time we have a “)” bracket symbol around.

Remember in the syntax above since we are passing an object in the parameters, you need to create your method in such a way so as to hold the object of the class or interface you are inheriting.

Anonymous Inner Class as an Argument Example

I am going to take the above example where our interface Water has:

interface Water { 

      void swish();  

}

with the method swish() that we are going to override.

We also have a class called Fire which has its very own method burn() where we will pass the parameter as an object of Interface Water:

public class Fire { 

       public void burn(Water w) { 

            System.out.println("Crazy"); 

      }  
}

So far so good?

Now we will come to our main method where we will use our syntax to write the code that matters:

using a main method to pass an anonymous class

So we are instantiating Fire() first so we could use its reference to call its burn() method where we are supposed to pass our Interface’s object as a parameter.

Whilst instantiating it using new Water() we are going to follow it up with method declaration as per our syntax. Don’t forget to close it with a ); sign.

If you will run the above program now it will give you the following result:

Crazy

The reason you got this result is because we are calling the burn() method in reality by passing the Interface object. So it will take you to that code, and execute whatever it contains.

As Java 8 ushers in with a whole lot of improvements and features, the use of Java anonymous inner class has been replaced by Lambda Expressions. We will see that concept at a later point.

Hope you have a solid understanding of anonymous inner classes now. That was one hell of a ride though. You did good soldier!

Scottshak

Poet. Author. Blogger. Screenwriter. Director. Editor. Software Engineer. Author of "Songs of a Ruin" and proud owner of four websites and two production houses. Also, one of the geekiest Test Automation Engineers based in Ahmedabad.

You may also like...

3 Responses

  1. July 10, 2017

    […] will see this new Java GUI example by bringing to use our anonymous inner class learning. If you don’t remember please just flip back (click on the […]

  2. July 11, 2017

    […] the location of a button and a text field we have chosen our own layout. We have made use of anonymous inner classes in Java to use the addActionListener method. Then we have overriden the actionPerformed method where the […]

  3. November 24, 2017

    […] If you don’t understand the way this syntax ends, you can check out our Anonymous Inner Classes Tutorial. […]

Leave a Reply