Anonymous Inner Class Extending a Superclass Tutorial

An anonymous inner class is a nested class defined without any name. An anonymous class is entirely dependent upon either a superclass or interface in order to work properly. This tutorial will focus on the version that dependent upon a superclass.
class HelloWorld {
     void displayMessage() {
         System.out.println("Hello World");
    }
}
class Tester {
     public static void main(String args[]){
         HelloWorld hw = new HelloWorld() {
             void displayMessage() {
                 System.out.println("Hello Earth");
             }
         };
         hw.displayMessage();
     }
}
In the example above, the anonymous inner class begins with the opening curly brace directly after the new HelloWorld(), the anonymous inner class ends at the closing curly brace directly before the semicolon above the statement hw.displayMessage();. When hw.displayMessage(); is invoked the output to the console will be Hello Earth.
What purpose does an anonymous inner class serve? They are a fantastic shortcut when you simply want to override a method from a class without creating a bunch of clutter code to accomplish a simple task. In the example above we simply wanted to override the displayMessage() method. How would we do that without using an anonymous inner class? First we would need to create a brand new class that would extend HelloWorld. Second we would need override the displayMessage() method and to be thorough we would include an @Override annotation. Finally we would create an instance of the new subclass and invoke the displayMessage() method on that instance. So as you can see, the anonymous inner class streamlines our code.

Anonymous inner classes can show up in some unexpected places, I'll demonstrate that in the video tutorial using the code below.



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md AnonymousInner
C:\Java>cd AnonymousInner
C:\Java\AnonymousInner>Notepad AnonymousInner.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


class HelloWorld { // superclass
    void displayMessage() {
        System.out.println("Hello World");
    }
}

class Tester {
    public static void main(String args[]){
        HelloWorld hw = new HelloWorld() {
            void displayMessage() {
                System.out.println("Hello Earth");
            }
        };
        hw.displayMessage();
    }
}

class Tester2 {
    public static void main(String args[]){
        HelloWorld hw = new HelloWorld() {
            @Override
            void displayMessage() {
                System.out.println("Hello Earth");
            }
            void displayError() {
                System.out.println("Don\'t create new methods in an anonymous inner class.");
            }
        };
        hw.displayMessage();
        //hw.displayError();
    }
}

class Tester3 {
    public static void main(String args[]){
        reallyStrange(new HelloWorld());
        reallyStrange(new HelloWorld(){
                @Override
                void displayMessage(){
                    System.out.println("Really strange stuff!");
                }
            });
    }

    static void reallyStrange(HelloWorld hw){
        hw.displayMessage();
    }
}

Now switch back to the command prompt (CMD) and type in javac AnonymousInner.java and press Enter.
Now type in java AnonymousInner and press Enter.


C:\Java\AnonymousInner>javac AnonymousInner.java
C:\Java\AnonymousInner>java AnonymousInner
Hello Earth


Final thoughts

This is another one of those tutorials where if you are new to the concept then you should wait a day to let the concept sink in the watch the video again. I am a believer that frustration and confusion are simply signs that you are learning. Don't give up, keep reviewing until you have your ah-ha moment and then move on to the next thing. If everything makes sense, then you are ready to move on to my next tutorial where I will discuss anonymous inner classes that implement interfaces.


Tutorials