OOP · Advanced OOP
Anonymous Objects
Cleaner project structure.
- Improved encapsulation.
- Easier maintenance.
- Cleaner project structure.
Real-World Problem
Imagine you're developing a Student Management System where you only need to display a student's details once. Creating a reference variable for an object that will never be used again increases unnecessary code and memory usage. Java allows such one-time operations using Anonymous Objects. Why Do We Need Anonymous Objects?
In many applications, an object is required only for a single operation, such as calling a method or invoking a constructor.
Creating a separate reference variable for such temporary objects makes the code longer and less readable. Anonymous objects simplify this process by allowing developers to create and use an object immediately without storing it in a variable. This results in cleaner, shorter, and more efficient code. What is an Anonymous Object?
An Anonymous Object is an object that is created without assigning it to a reference variable. It is used immediately after creation and cannot be accessed again because no reference to the object is stored. Anonymous objects are mainly used for one-time method calls or constructor invocations.
Characteristics
- Created without a reference variable.
- Used only once.
- Cannot be reused after creation.
- Becomes eligible for garbage collection when no references exist.
- Reduces unnecessary variable declarations.
Anonymous Object for Method Call
Anonymous Object as Method Argument

When to Use Use anonymous objects when:
- An object is required only once.
- Calling a method immediately after object creation.
- Passing an object as a method argument.
- Writing short and readable code.
Advantages
- Reduces code length.
- Eliminates unnecessary reference variables.
- Improves readability.
- Suitable for temporary operations.
- Simplifies one-time object usage.

Create a one-off object (often an interface implementation) inline without naming a class.
interface Greeter {
void greet();
}
public class Main {
public static void main(String[] args) {
// Anonymous class: a Greeter defined and instantiated on the spot
Greeter g = new Greeter() {
public void greet() { System.out.println("Hello!"); }
};
g.greet();
// Anonymous object: used once, never stored
System.out.println(new StringBuilder("abc").reverse());
}
}