Java Anonymous Inner Classes

Anonymous Inner Classes :

A class which does not have name is called as anonymous inner class. Anonymous class can be created using two methods :

  1. By using the interface
  2. By using the abstract class

Anonymous Inner Classes are used for writing an interface implementation.

Method 1 : By using the interface

Consider the following simple program -

package com.c4learn.innerclass;
interface Writable {
     void write(String msg);
}
public class AnonymousClassExample {
     public static void main(String[] args) {
        Writable w1 = new Writable() {
           public void write(String msg) {
               System.out.println(msg);
               }
        }; // Note the semicolon
        w1.write("Writing Diary");
     }
}

Output :

Writing Diary

Explanation of Program :

In the above program we have created one interface having name “Writable”.

Writable w1 = new Writable() {
     public void write(String msg) {
         System.out.println(msg);
     }
};
  1. Instance of the inner class is created whose name is decided by the compiler which implements Writable interface.
  2. We can create an anonymous inner class by using the new keyword as shown in the above example
  3. Writable() is followed by the implementation of the write method.
  4. In order to instantiates the anonymous inner class semicolon is used to terminate the statement
Click here to download (Right click -> Save it as)

Method 2 : By using the abstract class

Consider the following simple program -

package com.c4learn.innerclass;
abstract class Writable {
    void write(String msg) {
    }
}
public class AnonymousClassExample {
   public static void main(String[] args) {
       Writable w1 = new Writable() {
           public void write(String msg) {
              System.out.println(msg);
           }
       }; // Note the semicolon
	   w1.write("Writing Diary");
   }
}

Output :

Writing Diary

We can create Anonymous Inner Classes using the abstract class.

abstract class Writable {
    void write(String msg) {
    }
}
Click here to download (Right click -> Save it as)