Java Tutorial

Operators

Flow Control

String

Number and Date

Built-in Classes

Array

Class and Object

Inheritance and Polymorphism

Exception Handling

Collections, Generics and Enumerations

Reflection

Input/Output Stream

Annotation

Java Anonymous Class, Java Anonymous Inner Class

In Java, an anonymous inner class is a class without a name that is created as part of a class, method, or expression. Anonymous inner classes are commonly used to provide a concise way to define an implementation of an interface or to subclass a class. In this tutorial, you will learn how to create and use anonymous inner classes in Java.

  • Define an interface

First, let's define a simple interface called Greeting:

public interface Greeting {
    void sayHello();
}
  • Create an anonymous inner class

Now, let's create an anonymous inner class that implements the Greeting interface. This will be done within the main method of a class called AnonymousInnerClassDemo:

public class AnonymousInnerClassDemo {
    public static void main(String[] args) {
        // Create an anonymous inner class that implements the Greeting interface
        Greeting greeting = new Greeting() {
            @Override
            public void sayHello() {
                System.out.println("Hello from the anonymous inner class!");
            }
        };

        // Call the sayHello method on the anonymous inner class
        greeting.sayHello();
    }
}

In this example, we create an anonymous inner class that implements the Greeting interface and provides an implementation for the sayHello method. Then, we call the sayHello method on the anonymous inner class to see the output.

  • Create an anonymous inner class that extends a class

Anonymous inner classes can also be used to extend existing classes. Here, we create an anonymous inner class that extends the Thread class:

public class AnonymousInnerClassDemo {
    public static void main(String[] args) {
        // Create an anonymous inner class that extends the Thread class
        Thread myThread = new Thread() {
            @Override
            public void run() {
                System.out.println("Running the anonymous inner class thread.");
            }
        };

        // Start the anonymous inner class thread
        myThread.start();
    }
}

In this example, we create an anonymous inner class that extends the Thread class and provides an implementation for the run method. Then, we start the anonymous inner class thread to see the output.

  • Run the program

Now, compile and run the AnonymousInnerClassDemo class, and you should see the following output (the output may vary depending on which example you are running):

Hello from the anonymous inner class!

or

Running the anonymous inner class thread.

This tutorial demonstrates how to create and use anonymous inner classes in Java. Anonymous inner classes provide a concise and convenient way to implement interfaces or extend classes without having to create a separate named class.

  1. Anonymous Inner Class in Java Examples: Anonymous inner classes are defined and instantiated at the same time, typically used for overriding methods or implementing interfaces.

    interface Greeting {
        void greet();
    }
    
    public class GreetExample {
        public static void main(String[] args) {
            Greeting anonymousGreet = new Greeting() {
                @Override
                public void greet() {
                    System.out.println("Hello from anonymous class!");
                }
            };
    
            anonymousGreet.greet();
        }
    }
    
  2. Creating Anonymous Classes in Java: Anonymous classes are created without a separate class declaration. They are often used for quick, one-time implementations.

    Runnable myRunnable = new Runnable() {
        @Override
        public void run() {
            System.out.println("Anonymous class is running!");
        }
    };
    
  3. Using Anonymous Classes for Event Handling in Java: Anonymous classes are commonly used for event handling in GUI applications.

    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("Button clicked!");
        }
    });
    
  4. Java Anonymous Class with Interface: Anonymous classes are frequently used to implement interfaces in a concise manner.

    interface Shape {
        void draw();
    }
    
    public class Drawing {
        public static void main(String[] args) {
            Shape circle = new Shape() {
                @Override
                public void draw() {
                    System.out.println("Drawing a circle");
                }
            };
    
            circle.draw();
        }
    }
    
  5. Java Anonymous Class Constructor: Anonymous classes can have constructors, and they are invoked during the instantiation of the anonymous class.

    MyInterface myObject = new MyInterface() {
        // Anonymous class constructor
        {
            System.out.println("Anonymous class instantiated!");
        }
    
        @Override
        public void myMethod() {
            System.out.println("Method in anonymous class");
        }
    };
    
  6. Java Anonymous Class and Inheritance: Anonymous classes can extend a class or implement an interface. They can also access final variables from the enclosing scope.

    abstract class Animal {
        abstract void makeSound();
    }
    
    public class AnonymousInheritance {
        public static void main(String[] args) {
            Animal cat = new Animal() {
                @Override
                void makeSound() {
                    System.out.println("Meow!");
                }
            };
    
            cat.makeSound();
        }
    }
    
  7. Creating Anonymous Classes for Listeners in Java: Anonymous classes are commonly used for creating event listeners in GUI applications.

    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("Button clicked!");
        }
    });
    
  8. Java Anonymous Class for Thread Creation: Anonymous classes can be used to create threads by extending the Thread class or implementing the Runnable interface.

    Thread myThread = new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("Thread is running!");
        }
    });
    
  9. Anonymous Class Implementation for Abstract Classes in Java: Anonymous classes can also implement abstract classes.

    abstract class AbstractExample {
        abstract void abstractMethod();
    }
    
    public class Main {
        public static void main(String[] args) {
            AbstractExample example = new AbstractExample() {
                @Override
                void abstractMethod() {
                    System.out.println("Abstract method implemented!");
                }
            };
    
            example.abstractMethod();
        }
    }
    
  10. Java Nested Anonymous Classes: Anonymous classes can be nested within other classes or methods.

    public class Outer {
        void outerMethod() {
            Runnable myRunnable = new Runnable() {
                @Override
                public void run() {
                    System.out.println("Nested anonymous class running!");
                }
            };
            myRunnable.run();
        }
    }