An anonymous object in Java is an object that is created without assigning it to a reference variable. It is generally used when an object is needed only once and there is no requirement to reuse it later. Anonymous objects help reduce code and save memory by avoiding unnecessary references.
- They are typically used for one-time operations.
- They can directly call methods or be passed as method arguments.
Syntax
new ClassName().methodName();
Example: Calling a Method Using an Anonymous Object
import java.io.*;
class Person {
String name;
int age;
Person(String name, int age)
{
this.name = name;
this.age = age;
}
void display()
{
System.out.println("Name: " + name
+ ", Age: " + age);
}
}
public class Main {
public static void main(String[] args)
{
// Create an anonymous object
// and call its display method
new Person("John", 30).display();
}
}
Output
Name: John, Age: 30
Explanation: In this example, an object of the Person class is created with the values "John" and 30. The object is not assigned to any variable, and the display() method is called immediately, printing the person's details.
Example: Anonymous Object with Inner Class
import java.io.*;
class OuterClass {
class InnerClass {
void display()
{
System.out.println("Inside InnerClass");
}
}
public static void main(String[] args)
{
// Create an anonymous object of the InnerClass and
// call its display method
new OuterClass().new InnerClass().display();
}
}
Output
Inside InnerClassExplanation: Here, an anonymous object of OuterClass is first created. Then an anonymous object of InnerClass is created using that outer object, and the display() method is called directly without storing any object reference.
Anonymous Object vs Named Object
| Anonymous Object | Named Object |
|---|---|
| No reference variable | Stored in a reference variable |
| Used once | Can be reused multiple times |
| Less code | More flexible |
| Cannot be accessed again | Can be accessed anytime |
Advantages of Anonymous Objects
- Reduces code by eliminating unnecessary reference variables.
- Saves memory when an object is used only once.
- Makes code concise and readable for simple operations.
- Useful for passing temporary objects as method arguments.
- Commonly used with inner classes, anonymous classes, and lambda expressions.
- Avoids creating extra variables that are not reused.