DEV Community

Sanjay Prajapat
Sanjay Prajapat

Posted on • Edited on • Originally published at sanjayprajapat.hashnode.dev

Java Anonymous Inner Class

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

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");
    }
}

Enter fullscreen mode Exit fullscreen mode
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 
    }    
}

Enter fullscreen mode Exit fullscreen mode

Anonymous class with Interface

interface I1{
    void fun1();
}

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

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
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)