Anonymous Inner Class in Java
Last Updated :
09 Jul, 2024
Nested Classes in Java is prerequisite required before adhering forward to grasp about anonymous Inner class. It is an inner class without a name and for which only a single object is created. An anonymous inner class can be useful when making an instance of an object with certain “extras” such as overriding methods of a class or interface, without having to actually subclass a class.
Tip: Anonymous inner classes are useful in writing implementation classes for listener interfaces in graphics programming.Â
The syntax of an anonymous class expression is like the invocation of a constructor, except that there is a class definition contained in a block of code.Â
Syntax:
// Test can be interface,abstract/concrete class
Test t = new Test()
{
// data members and methods
public void test_method()
{
........
........
}
};
Now let us do discuss the difference between regular class(normal classes) and Anonymous Inner class
- A normal class can implement any number of interfaces but the anonymous inner class can implement only one interface at a time.
- A regular class can extend a class and implement any number of interfaces simultaneously. But anonymous Inner class can extend a class or can implement an interface but not both at a time.
- For regular/normal class, we can write any number of constructors but we can’t write any constructor for anonymous Inner class because the anonymous class does not have any name and while defining constructor class name and constructor name must be same.
Accessing Local Variables of the Enclosing Scope, and Declaring and Accessing Members of the Anonymous ClassÂ
Like local classes, anonymous classes can capture variables; they have the same access to local variables of the enclosing scope:Â Â
- An anonymous class has access to the members of its enclosing class.
- An anonymous class cannot access local variables in its enclosing scope that are not declared as final or effectively final.
- Like a nested class, a declaration of a type (such as a variable) in anonymous class shadows any other declarations in the enclosing scope that have the same name.
Anonymous classes also have the same restrictions as local classes with respect to their members:Â
- We cannot declare static initializers or member interfaces in an anonymous class.
- An anonymous class can have static members provided that they are constant variables.
Note: We can declare the following in anonymous classes as follows:
- Fields
- Extra methods (even if they do not implement any methods of the supertype)
- Instance initializers
- Local classes
Ways:
Anonymous inner classes are generic created via below listed two ways as follows:Â
- Class (may be abstract or concrete)
- Interface
Now let us take an example with which we will understand anonymous inner class, let us take a simple program
Example
Java
// Java program to demonstrate Need for
// Anonymous Inner class
// Interface
interface Age {
// Defining variables and methods
int x = 21;
void getAge();
}
// Class 1
// Helper class implementing methods of Age Interface
class MyClass implements Age {
// Overriding getAge() method
@Override public void getAge()
{
// Print statement
System.out.print("Age is " + x);
}
}
// Class 2
// Main class
// AnonymousDemo
class GFG {
// Main driver method
public static void main(String[] args)
{
// Class 1 is implementation class of Age interface
MyClass obj = new MyClass();
// calling getage() method implemented at Class1
// inside main() method
obj.getAge();
}
}
Output:

Output explanation:
In the above program, interface Age is created with getAge() method and x=21.  Myclass is written as an implementation class of Age interface. As done in Program, there is no need to write a  separate class Myclass. Instead,  directly copy the code of Myclass into this parameter, as shown here:Â
Age oj1 = new Age()
{
@Override
public void getAge()
{
System.out.print("Age is " + x);
}
};
Here, an object to Age is not created but an object of Myclass is created and copied in the entire class code as shown above. This is possible only with anonymous inner class. Such a class is called ‘anonymous inner class’, so here we call ‘Myclass’ as anonymous inner class.
Example:
Java
// Java Program to Demonstrate Anonymous inner class
// Interface
interface Age {
int x = 21;
void getAge();
}
// Main class
class AnonymousDemo {
// Main driver method
public static void main(String[] args)
{
// A hidden inner class of Age interface is created
// whose name is not written but an object to it
// is created.
Age oj1 = new Age() {
@Override public void getAge()
{
// printing age
System.out.print("Age is " + x);
}
};
oj1.getAge();
}
}
Types of Anonymous Inner Class
Based on declaration and behavior, there are 3 types of anonymous Inner classes:Â
- Anonymous Inner class that extends a class
- Anonymous Inner class that implements an interface
- Anonymous Inner class that defines inside method/constructor argument
Type 1: Anonymous Inner class that extends a class
We can have an anonymous inner class that extends a class. For example, we know that we can create a thread by extending a Thread class. Suppose we need an immediate thread but we don’t want to create a class that extends Thread class all the time. With the help of this type of Anonymous Inner class, we can define a ready thread.
Example
Java
// Java program to illustrate creating an immediate thread
// Using Anonymous Inner class that extends a Class
// Main class
class MyThread {
// Main driver method
public static void main(String[] args)
{
// Using Anonymous Inner class that extends a class
// Here a Thread class
Thread t = new Thread() {
// run() method for the thread
public void run()
{
// Print statement for child thread
// execution
System.out.println("Child Thread");
}
};
// Starting the thread
t.start();
// Displaying main thread only for readability
System.out.println("Main Thread");
}
}
OutputMain Thread
Child Thread
Type 2: Anonymous Inner class that implements an interface
We can also have an anonymous inner class that implements an interface. For example, we also know that by implementing Runnable interface we can create a Thread. Here we use an anonymous Inner class that implements an interface.
Example
Java
// Java program to illustrate defining a thread
// Using Anonymous Inner class that implements an interface
// Main class
class MyThread {
// Main driver method
public static void main(String[] args)
{
// Here we are using Anonymous Inner class
// that implements a interface i.e. Here Runnable
// interface
Runnable r = new Runnable() {
// run() method for the thread
public void run()
{
// Print statement when run() is invoked
System.out.println("Child Thread");
}
};
// Creating thread in main() using Thread class
Thread t = new Thread(r);
// Starting the thread using start() method
// which invokes run() method automatically
t.start();
// Print statement only
System.out.println("Main Thread");
}
}
OutputMain Thread
Child Thread
Type 3: Anonymous Inner class that defines inside method/constructor argument
Anonymous inner classes in method/constructor arguments are often used in graphical user interface (GUI) applications. To get you familiar with syntax lets have a look at the following program that creates a thread using this type of Anonymous Inner class
Example
Java
// Java program to illustrate defining a thread
// Using Anonymous Inner class that define inside argument
// Main class
class MyThread {
// Main driver method
public static void main(String[] args)
{
// Using Anonymous Inner class that define inside
// argument
// Here constructor argument
Thread t = new Thread(new Runnable() {
public void run()
{
System.out.println("Child Thread");
}
});
t.start();
System.out.println("Main Thread");
}
}
OutputMain Thread
Child Thread
However, constructors can not be declared in an anonymous class.
Similar Reads
Classes and Objects in Java
In Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are used to represent real-world concepts and entities. The class represents a group of objects having similar properties and behavior, or in other words, we can say that a class is a blueprint for objects, wh
12 min read
Understanding Classes and Objects in Java
The term Object-Oriented explains the concept of organizing the software as a combination of different types of objects that incorporate both data and behavior. Hence, Object-oriented programming(OOPs) is a programming model, that simplifies software development and maintenance by providing some rul
10 min read
Inner Class in Java
In Java, inner class refers to the class that is declared inside class or interface which were mainly introduced, to sum up, same logically relatable classes as Java is object-oriented so bringing it closer to the real world. Now geeks you must be wondering why they were introduced? There are certai
11 min read
Anonymous Inner Class in Java
Nested Classes in Java is prerequisite required before adhering forward to grasp about anonymous Inner class. It is an inner class without a name and for which only a single object is created. An anonymous inner class can be useful when making an instance of an object with certain "extras" such as o
7 min read
Nested Classes in Java
In Java, it is possible to define a class within another class, such classes are known as nested classes. They enable you to logically group classes that are only used in one place, thus this increases the use of encapsulation and creates more readable and maintainable code. The scope of a nested cl
5 min read
Java.util.Objects class in Java
Java 7 has come up with a new class Objects that have 9 static utility methods for operating on objects. These utilities include null-safe methods for computing the hash code of an object, returning a string for an object, and comparing two objects. Using Objects class methods, one can smartly handl
7 min read
Different Ways to Create Objects in Java
Java is an object-oriented programming language where objects are instances of classes. Creating objects is one of the most fundamental concepts in Java. In Java, a class provides a blueprint for creating objects. Most of the time, we use the new keyword to create objects but Java also offers severa
5 min read
How are Java Objects Stored in Memory?
In Java, all objects are dynamically stored in the Heap memory while references to those objects are stored in the stack. Objects are created with the help of "new" keyword and are allocated in the heap memory. However, declaring a variable of a class type does not create an object it only creates r
5 min read
Passing and Returning Objects in Java
Although Java is strictly passed by value, the precise effect differs between whether a primitive type or a reference type is passed. When we pass a primitive type to a method, it is passed by value. But when we pass an object to a method, the situation changes dramatically, because objects are pass
6 min read
Java Lambda Expressions
Lambda expressions in Java, introduced in Java SE 8, represent instances of functional interfaces (interfaces with a single abstract method). They provide a concise way to express instances of single-method interfaces using a block of code. Functionalities of Lambda ExpressionLambda Expressions impl
5 min read