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

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs