Anonymous Inner Class in Java

An anonymous inner class in Java is a special type of inner class that is declared without any class name at all. In other words, an anonymous inner class is a nameless local class that is defined and instantiated in a single step.

Anonymous inner classes are useful when you need to create only one instance of a class or interface implementation and do not need to reuse the class elsewhere. This makes the code shorter and avoids creating a separate named class.

Since an anonymous inner class does not have a class name, you cannot declare a constructor in it. This is because a constructor must have the same name as the class, and an anonymous class has no name; it cannot declare one.

Then how do we create an object of an anonymous class in Java if it does not have a constructor? Let’s understand this concept.

How to Create Object of Anonymous Inner Class in Java?


An anonymous inner class in Java is generally a one-time class. It is used when a class or interface implementation is required only once. You can declare and instantiate an anonymous inner class simultaneously using the new operator in a single expression.

The general syntax for creating an anonymous inner class and its object is as follows:

new <class-name or interface-name>(argument-list)
{
  // Anonymous class body
};

In this syntax:

  • The new keyword is used to create an object of an anonymous inner class. It is always followed by the name of an existing class or interface.
  • If new is followed by an interface name, it means that the anonymous class implements that interface.
  • If new is followed by a class name, it means that the anonymous class extends that class.
  • When the new keyword is followed by a class name, the argument list contains the actual arguments passed to a constructor of the superclass. These arguments are used to invoke the constructor of the class being extended (i.e., superclass).
  • When the new keyword is followed by an interface name, the parentheses are still required, but the argument list is always empty because interfaces do not have constructors.
  • Inside the anonymous class body, you can declare the following:
    • Instance variables (fields)
    • Instance methods
    • Instance initializer blocks
    • Local classes
    • Nested interfaces and enums (where permitted by Java language rules)
  • You must place a semicolon (;) after the closing brace because the entire anonymous class declaration is part of an object creation expression, and the expression must be terminated with a semicolon.

Java Anonymous Inner Class Constructor


Since an anonymous inner class has no name, it is not possible to define a constructor for it within the class body. Constructors must have the same name as the class, and an anonymous class has no name.

When to Use Anonymous Inner Class in Java?


In general, there are the following points that you should consider using an anonymous inner class in Java instead of a local inner class.

  • The main purpose of using an anonymous inner class in Java is just for instant use (i.e., one-time usage).
  • An anonymous inner class can be used if the class has a very short body.
  • It is useful when the class implementation is needed only once and is not intended to be reused.
  • An anonymous inner class is useful in Java programming when you are writing implementation classes for listener interfaces in graphics programming.
  • Anonymous inner classes are commonly used for implementing event handling in GUI-based applications.

Important Notes

  1. If the requirement is standard and required several times, then you should go for a normal top-level class.
  2. If the requirement is temporary and required only once (instant use), you should go for Java anonymous inner class.

Features of Anonymous Inner Class


An anonymous inner class is a special kind of inner class in Java with the following important features:

  1. When an anonymous inner class is created, internally, the compiler automatically assigns a name to an anonymous inner class. It always extends a superclass or implements an interface, but it cannot explicitly use the extends or implements keywords.
  2. If the anonymous class extends an abstract class or implements an interface, it must provide implementations for all inherited abstract methods.
  3. An anonymous inner class cannot declare its own constructor. When an object of an anonymous class is created, the constructor of its superclass is invoked using the arguments passed in the object creation expression.
  4. The Java compiler generates a separate class file for each anonymous inner class. The generated class is typically named OuterClassName$1.class, OuterClassName$2.class, and so on. For example, if the outer class Student has two anonymous inner classes, they are compiled into Student$1.class and Student$2.class.
  5. Like the local inner class, an anonymous inner class can access all members of its enclosing class, including private members. It can also access local variables that are final or effectively final.

Types of Anonymous Inner Class in Java


Based on declaration and behavior, anonymous inner classes in Java are of two types:

  1. Anonymous inner class that extends a class
  2. Anonymous inner class that implements an interface

Let’s understand them one by one with the help of example programs.

Anonymous Inner Class that Extends Class


Example 1:

Let’s take an example in which we will create an anonymous inner class that extends a Fruits class.

public class Fruits 
{ 
  public void mango() 
  { 
    System.out.println("Sweet"); 
  } 
  // Suppose we also declared 9 more fruit-related methods. 
  // Therefore, the total number of methods in the Fruits class is 10. 
}

Now suppose we want the mango() method to display “Sour” instead of “Sweet” for a one-time (temporary) requirement. We want to override only this method while keeping the remaining nine methods unchanged. How can we implement this in the above code?

There are two ways to implement inside the above code.

1. First Way

The first way is to create a subclass of Fruits and override the mango() method. This approach is suitable when the modified behavior is required repeatedly rather than only once.

2. Second Way

The second way is to use an anonymous inner class concept for a one-time temporary requirement. Look at the code below to understand better.

public class Taste { 
public static void main(String[] args) 
{ 
// Here, we are using an anonymous inner class that extends a class Fruits. 
   Fruits f = new Fruits() 
   { 
  // Override the mango() method of Fruits class. 
     public void mango() 
     { 
       System.out.println("Sour"); 
     } 
   }; // Anonymous inner class ends here. A semi-colon is necessary to end the statement. 

   f.mango(); 
// Creates an object of Fruits class. 
   Fruits f1 = new Fruits(); 
   f1.mango(); // It will print sweet. 
  } 
}

Output:

Sour 
Sweet

Internal Working of the Given Code

Fruits f = new Fruits() 
{ 
    public void mango() 
    { 
       System.out.println("Sour"); // Overriding. 
    } 
}; // Anonymous inner class ends here.

1. The statement Fruits f = new Fruits() { creates an instance of an anonymous subclass of Fruits, whose reference is assigned to the variable f of type Fruits. Internally, the Java compiler generates an anonymous subclass of Fruits and assigns it a synthetic name. This generated subclass overrides the mango() method. The opening curly brace ({) marks the beginning of the anonymous class body.

2. Inside the anonymous class body, we override the mango() method inherited from the Fruits class.

3. The statement System.out.println(“Sour”); inside the overridden mango() method prints “Sour” when the method is invoked.

4. The closing curly brace (}) marks the end of the overridden mango() method.

5. The next closing curly brace (}) marks the end of the anonymous inner class definition. It is followed by a semicolon (;), which terminates the object creation expression.

Dot Class File Generated by the Compiler

The Java compiler generates a total of three .class files:

  1. The first .class file generated for the Fruits class is Fruits.class.
  2. The second dot class file generated by the compiler for the Taste class is Taste.class.
  3. The compiler also generates a separate .class file for the anonymous inner class because it is declared inside the Taste class.

Since the anonymous inner class is declared inside the Taste class, Taste is its enclosing (outer) class. Therefore, the Java compiler typically generates a class file named Taste$1.class, where 1 indicates the first anonymous inner class declared within the Taste class.

Anonymous Inner Class that Implements Interface


Example 2:

Let’s take an example in which an anonymous inner class implements the Animal interface.

public interface Animal 
{ 
// Abstract method does not have a body. 
   public void food();
} 
public class Lion 
{ 
// Here, we are using an anonymous inner class that implements the Animal interface. 
   Animal a = new Animal() 
   { 
      // Overriding food method of Interface Animal. 
      public void food() 
      { 
         System.out.println("Lion eats flesh"); 
      } 
   }; 
   public void display() 
   { 
      a.food(); 
   } 
} 
public class Test{ 
   public static void main(String[] args) 
   { 
       Lion l = new Lion(); 
       // 1st method to call an anonymous function by local class method.
       l.display();  
      // 2nd method to call an anonymous function directly.
       l.a.food();  
   } 
}

Output:

Lion eats flesh 
Lion eats flesh

Internal Working of the Given Code

Animal a = new Animal()
{ 
  public void food()
  { 
     System.out.println("Lion eats flesh"); 
  }  
 }; // Anonymous inner class ends here.

1. The statement Animal a = new Animal() { creates an instance of an anonymous class that implements the Animal interface. The reference to this object is assigned to the reference variable a of type Animal. Internally, the Java compiler generates an anonymous class that implements the Animal interface and assigns it a synthetic name.

2. Within the anonymous class body, we provide an implementation of the food() method declared in the Animal interface.

Restriction on Anonymous Inner Class


An anonymous inner class has many of the same restrictions as a local inner class. The important restrictions are as follows:

  1. An anonymous inner class cannot be declared with an access modifier (public, protected, or private) or with the static modifier because it has no explicit class declaration.
  2. It can access only those local variables and parameters of its enclosing scope that are final or effectively final.
  3. Inside anonymous inner classes, you cannot define any static variables, static methods, or static blocks except for static final compile-time constants.
  4. Since an anonymous inner class has no name, you cannot declare a constructor within its class body.
  5. You cannot explicitly extend or instantiate an anonymous inner class elsewhere because it has no name.

Difference between Normal Class and Anonymous Inner Class


The important difference between a normal class and an anonymous inner class in Java is as follows:

1. A normal Java class can explicitly implement one or more interfaces. An anonymous inner class can explicitly implement only one interface because it is created by specifying a single interface after the new keyword.

2. A normal Java class can extend one class and implement one or more interfaces simultaneously. An anonymous inner class can either extend a class or implement a single interface, but it cannot explicitly do both at the same time.

3. In a normal Java class, you can define one or more constructors. In an anonymous inner class, you cannot declare a constructor explicitly because the name of the class and the name of the constructor must be the same, but an anonymous inner class does not have any name.

DEEPAK GUPTA

DEEPAK GUPTA

Deepak Gupta is the Founder of Scientech Easy, a Full Stack Developer, and a passionate coding educator with 8+ years of professional experience in Java, Python, web development, and core computer science subjects. With strong expertise in full-stack development, he provides hands-on training in programming languages and in-demand technologies at the Scientech Easy Institute, Dhanbad.

He regularly publishes in-depth tutorials, practical coding examples, and high-quality learning resources for both beginners and working professionals. Every article is carefully researched, technically reviewed, and regularly updated to ensure accuracy, clarity, and real-world relevance, helping learners build job-ready skills with confidence.