Anonymous Inner Classes

Having dealt with inner classes in earlier posts this post deals with anonymous inner classes – an even more different type of code that causes more confusion for the amateur programmer.

What are anonymous inner classes?

‘Anonymous inner classes’ or ‘Anonymous classes’ as the name suggests is creating an inner class with no name. Here is a simple program that illustrates the working of the anonymous class.

Program 1:

//Program to illustrate anonymous inner class
package whizlabs;
 class anon_1 {
     public static void main(String args[]){   
           pgm p1=new pgm();
               pgm p=new pgm(){ // start of anonymous inner class
                 String s="whizlabs";
                  public void simple(){
                      System.out.println(s + " world");
                 }
                     }; // end of the anonymous inner class 
                     p.simple();
                     p1.simple();
     }
     }
class pgm{
           public void simple(){
           System.out.println("hello");
     }
}

Output:
whizlabs world
hello

These are some key points:

  1. The above example shows two classes ‘anon_1’ and ‘pgm’ .
  2. The class ‘pgm’ has a method ‘simple’ which just prints a message ‘hello’.

The main idea behind using anonymous inner classes is to override a method without the hassle of having to create a whole new class.

This is the anonymous class code segment:

               pgm p=new pgm(){ // start of anonymous inner class
                 String s="whizlabs";
                  public void simple(){
                      System.out.println(s + " world");
                 }
                     }; // end of the anonymous inner class

Notice that the place where a semi-colon is normally present, an open paranthesis is present

pgm p=new pgm(){

This signals the start of the anonymous class.

This class is now actually a sub-class of the ‘pgm’ class but with no name! The instance variable ‘p’ is created without the anonymous inner class even having a name. This anonymous class effectively allows us to override the ‘simple’ method in our case.

The anonymous inner class is finally closed by a ‘semi-colon’ at the end of a brace.

}; // end of the anonymous inner class

p.simple() when invoked calls the overridden method ‘simple’ within the anonymous class and the appropriate output is printed.  p1.simple() on the other hand invokes the super class’s method and the appropriate output is printed out.

Having seen this, let us see what happens when non-overriden method is introduced in the anonymous class.

Program 2: Non-overriden method in anonymous class:

//Program to illustrate anonymous inner class

package whizlabs;
 class anon_1 {
     public static void main(String args[]){   
           pgm p1=new pgm();
               pgm p=new pgm(){ // start of anonymous inner class
                 String s="whizlabs";
                  public void simple(){
                      System.out.println(s + " world");
                 }
                  // Non-overridden method in anonymous class
                  public void another(){
                       System.out.println("another method");
                  }
                     }; 
          p.simple();
           p.another();// trying to invoke the non-overridden method
                p1.simple(); 
     }
     }
class pgm{ 
           public void simple(){
           System.out.println("hello");
     }
}

Explanation:
This program shows a non-overridden method ‘another’ in the anonymous class.

       public void another(){
                       System.out.println("another method");
                  }

Just declaring it will not cause problems – however invoking it, the following way:

p.another();

will cause compiler error.
This is the error that will be generated:

Exception in thread “main” java.lang.Error: Unresolved compilation problem:
       The method another() is undefined for the type pgm
       at whizlabs.anon_1.main(anon_1.java:18)  (Kathy Sierra)

Why is this error generated? It is because of polymorphism. Note that even though the variable ‘p’ refers to the anonymous sub-class , it is of the super-class ‘pgm’ type. Since the class ‘pgm’ does not have ‘another’ method, an error is thrown.

In short, even though other methods can be declared within an anonymous inner class, they cannot be invoked. For how will we invoke a method that is within a class (that which has no name?)

Bibliography
In B. B. Kathy Sierra, Sun Certified Java Programmer for Java 6 Study Guide.

About Aditi Malhotra

Aditi Malhotra is the Content Marketing Manager at Whizlabs. Having a Master in Journalism and Mass Communication, she helps businesses stop playing around with Content Marketing and start seeing tangible ROI. A writer by day and a reader by night, she is a fine blend of both reality and fantasy. Apart from her professional commitments, she is also endearing to publish a book authored by her very soon.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top