Java Anonymous Classes: Simplifying One-Time Use Inner Classes

Explore Java anonymous classes, nameless inner classes ideal for one-time use. Learn how to define and use anonymous inner classes in Java to implement interfaces or extend classes efficiently, with examples on how to use the new operator for quick object creation.



Java - Anonymous Classes

An anonymous class in Java is an inner class declared without any class name. In other words, it is a nameless inner class. Since it does not have a name, it cannot have a constructor because a constructor's name must match the class name.

Use of Java Anonymous Inner Classes

Anonymous inner classes are useful when you need to create a simple class for one-time use, typically to implement an interface or extend a class.

Defining Anonymous Class in Java

You can define an anonymous inner class and create its object using the new operator in one step.

Syntax

new(argument-list) {
// Anonymous class body
}
    

Types of Anonymous Inner Classes in Java

  • Anonymous inner class that extends a class
  • Anonymous inner class that implements an interface
  • Anonymous inner class as an argument

1. Anonymous Inner Class that Extends a Class

An anonymous inner class can extend a class in Java.

Example: Anonymous inner class that extends a class

package com.tutorialsarena;

class Car {
public void engineType() {
    System.out.println("Turbo Engine");
}
}

public class Tester {
public static void main(String args[]) {
    Car c1 = new Car();
    c1.engineType();
    
    Car c2 = new Car() {
        @Override
        public void engineType() {
        System.out.println("V2 Engine");
        }
    };
    c2.engineType();
}
}
    
Output

Turbo Engine
V2 Engine
    

2. Anonymous Inner Class that Implements an Interface

An anonymous inner class can implement an interface in Java.

Example: Anonymous inner class that implements an interface

package com.tutorialsarena;

interface Software {
public void develop();
}

public class Tester {
public static void main(String args[]) {
    Software s = new Software() {
        @Override
        public void develop() {
        System.out.println("Software Developed in Java");
        }
    };
    s.develop();
    System.out.println(s.getClass().getName());
}
}
    
Output

Software Developed in Java
com.tutorialsarena.Tester$1
    

3. Anonymous Inner Class as an Argument

Anonymous inner classes can also be passed as arguments to methods or constructors.

Example: Anonymous inner class as an argument

package com.tutorialsarena;

abstract class Engine {
public abstract void engineType();
}

class Vehicle {
public void transport(Engine e) {
    e.engineType();
}
}

public class Tester {
public static void main(String args[]) {
    Vehicle v = new Vehicle();
    v.transport(new Engine() {
        @Override
        public void engineType() {
        System.out.println("Turbo Engine");
        }
    });
}
}
    
Output

Turbo Engine