Java Anonymous Inner Class

Latest posts
Get notified of the Latest Sport News Update from Our Blog
Share

A nested class doesn’t have any name is Known as anonymous inner class. anonymous inner class can be used in two ways

1. for overriding purpose

If the purpose of class is only to override method ex: purpose of creating B class to override fun1 in this case you don’t need to create B class

class A{
    void fun1(){
        System.out.println("fun1 in A ");
    }
}
class B extends A{
    void fun1(){
        System.out.println("fun1 in B");
    }
}
public class Program1
{
    public static void main(String[] args) {
        // A a = new B();
        // a.fun1(); //fun1 in B

        A obj = new A(){
            void fun1() {
                System.out.println("Anonymous Overidden method ");
            }
            // can't create 
            // void fun2(){
            //     System.out.println("fun2 method ");
            // }
        };
        obj.fun1(); // Anonymous Overidden method 
    }    
}

Anonymous class with Interface

interface I1{
    void fun1();
}

class Implementor implements I1{
    public void fun1(){
        System.out.println("Implementation of fun1");
    }
}

2. if role of implementor class is only to implement I1 interface , so you can create anonymous inner class , you don’t need to create implementor class

public class Program2 {
    public static void main(String[] args) {
        // Implementor i1 = new Implementor();
        // i1.fun1(); //Implementation of fun1

        I1 i = new I1(){
            public void fun1(){
                System.out.println("Anonymous implementation");
            }
        };
        i.fun1(); // Anonymous implementation
    }
}

Leave a Reply

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

Related blogs

Nullam quis risus eget urna mollis ornare vel eu leo. Aenean lacinia bibendum nulla sed 

Subscribe to get 15% discount