DEV Community

Sanjay Prajapat
Sanjay Prajapat

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

1 1

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

AWS Q Developer image

Your AI Code Assistant

Ask anything about your entire project, code and get answers and even architecture diagrams. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Start free in your IDE

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post