Anonymous inner class in Java with Example

Anonymous inner classes have been the most crucial part of Java that most programmers love to use. The syntax of these classes is very simple to learn or to fathom. These classes are in general used for implementing the abstract methods of either an abstract class or an interface.
We know that one cannot create an object for either an abstract class or an interface directly but can do it indirectly. One of the indirect way of doing this is writing a class that extends the abstract class or if it is an interface, writing a class that implements this interface. Then we'll create the object for that class and call it in the name the interface or it's super abstract class. Writing a class each time is a headache. So, it's better if we can just write a class with in the class itself.
You might encounter the concept of nested classes this time. But let's try the anonymous inner classes. I've previously used the concept of anonymous inner classes very previously in many posts especially in Threading and Swing concepts. Now let us see an example of this here.


 abstract class AE
{
int n;
  
    public AE(int n)
    {
    this.n=n;
    }
    public abstract void myMethAE();
    public void myMethBE()
    {
    System.out.println("My Meth BE | n:"+n);
    }
}
class AnonymousExample
{
    public static void main(String args[])
    {
    AE a=new AE(2){
            public void myMethAE(){
            System.out.println("myMethAE | n:"+n);}
            public void myMethBE(){
            System.out.println("My Meth BE");
            }
        };
  
    a.myMethAE();
    a.myMethBE();
    }
}

Output


myMethAE | n:2
My Meth BE

Explaining the code

new AE(2){//code}; Invoke the constructor in the class AE taking an int type variable as parameter.Open the braces, start implementing the abstract methods/override the existing ones (if necessary).

public void myMethAE(){} Write the implementation code for myMethAE in the braces (i.e. develop the body of this method).
In the same way for myMethBE() but here the method is overriden.

Note: Not only with abstract classes, you can also work out things with interfaces i.e. you can provide the implementation code for the methods defined in an interface in the same way. I have already done in many of my previous posts and Using JProgressBar with Thread class is one of them. Here the Runnable interface is implemented in the style above.

So, i think you are now clear about how to write anonymous inner classes in Java with this enunciating example. Drop a comment for queries.

No comments: