![]() |
VOOZH | about |
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.
new ClassName().methodName();
Example: Calling a Method Using an Anonymous Object
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
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 | 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 |