Anonymous object in Java

An object which has no reference variable is called anonymous object in Java. Anonymous means nameless. So, an anonymous object is an object without a specific name or reference variable.

An anonymous object is not stored in a named variable. In other words, when we initialize an object, but we do not assign it to any reference variable, it is called an anonymous object. For example:

new Student(); // anonymous object.

If we assign it to a reference variable like this:

Student st = new Student();

In the above code, st is a reference variable or named variable. Thus, it is not an anonymous object because we have assigned it to a reference variable st.

We can use an anonymous object at the time of object creation only. If you want to create only one object in a class, then the anonymous object is an excellent approach. Since an anonymous object has no name, we cannot access or reuse later in the code.

Syntax to Create Anonymous Object


We instantiate anonymous objects without assigning them to variables. This is especially useful when we need a temporary object for a single operation and do not need to persist in memory. The general syntax to create an anonymous object in Java is as below.

new Class_name(); // anonymous object.

For example:

new Student();

We can pass the parameter to the constructor like this:

new Student("Shubh");


If you want to call a method through the anonymous object, then we can write the code like this:

new Student().display(); // calling a method through anonymous object.

We can also pass the parameter to the calling method like this:

new Student().display("Shubh", 25);

Anonymous Example Programs for Best Practices


Let’s take a very simple example in which we will create an anonymous object. With an anonymous object, we will call a variable and methods.

Program code 1:

package anonymousObject;
public class Car
{
  String name = "Renault";	
  void start() {
	 System.out.println("Engine started.");
  }
  void stop() {
	 System.out.println("Engine stopped.");
  }
 public static void main(String[] args) 
 {
// Calling variable using anonymous object.
   System.out.println("Car name: " +new Car().name);

// Calling methods through anonymous object.
   new Car().start();
   new Car().stop();
  }
}
Output:
      Car name: Renault
      Engine started.
      Engine stopped.

Let’s take an example program where we will pass argument values to the constructor and methods through anonymous objects.


Program code 2:

package anonymousObject; 
public class Multiplication 
{ 
// Declare instance variables.
   int a; 
   int b; 
   int c; 
   int d; 
// Declare a parameterized constructor with parameters of type int. 
   Multiplication(int p, int q)
   { 
      a = p; 
      b = q; 
      int ab = a * b; 
      System.out.println("Multiplication of a and b:" +ab); 
   } 
// Declare an instance method with parameters of type int. 
   void multiply(int x, int y )
   { 
       c = x; 
       d = y; 
       int cd = c * d; 
       System.out.println("Multiplication of c and d:" +cd); 
   } 

public static void main(String[] args) 
{ 
// Create an anonymous object, pass the values to the constructor, and call the method. 
   new Multiplication(25, 25).multiply(10, 20); 

// We can also pass the different values with the same anonymous object. 
// but we cannot create another new anonymous object. 
     new Multiplication(20, 20).multiply(30, 30); 
  } 
}
Output: 
       Multiplication of a and b: 625 
       Multiplication of c and d: 200 
       Multiplication of a and b: 400 
       Multiplication of c and d: 900

Let’s take another example where we will create an anonymous object and calculate area and perimeter of the square by passing different values to constructor and method.

Program code 3:

package anonymousObject; 
public class Calculation 
{ 
// Declare an instance variable. 
   int a; 

// Declare one parameter constructor. 
   Calculation(int p)
   { 
      a = p; 
   } 
// Declare instance methods. 
   void area()
   { 
      int area = a * a; 
      System.out.println("Area of square: " +area); 
   } 
   void perimeter(int b)
   { 
     int peri = 4 * b; 
     System.out.println("Perimeter of square: " +peri); 
   } 

public static void main(String[] args)
{ 
// Create anonymous objects. 
     new Calculation(50).area(); 
     new Calculation(10).perimeter(100); 
     new Calculation(20).area(); 
     new Calculation(30).perimeter(200); 
  } 
}
Output: 
       Area of square: 2500 
       Perimeter of square: 400 
       Area of square: 400 
       Perimeter of square: 800

Advantages and Usage of Anonymous Objects in Java


There are the following advantages of using anonymous objects in Java. They are as:

  • An anonymous object simplifies code structure by eliminating the need for explicit object creation. It is especially useful for one-time operation where creating named objects would be unnecessary and cumbersome.
  • It is ideal for scenarios where an object is needed only for a single method call.
  • Usage of anonymous objects can make code more concise and readable because it eliminates the clutter of named object declarations and subsequent method calls.

Differences Between Anonymous and Named Objects


There are mainly two differences between anonymous and named objects. They are as:

(a) Naming Conventions and Scope:

We declare named objects with specific variable names, allowing them to be referenced throughout the program code. Anonymous objects, on the other hand, have no names and are limited in scope to the statement where we have created.

(b) Memory Utilization:

Anonymous objects are automatically eligible for garbage collection after use. They can lead to better memory management compared to named objects that might persist longer in memory.


Key Points:

1. A class that does not have a name is called anonymous class in Java. We can define it within a method without a name.

2. The object of an anonymous class is created in the same place where it is defined. It cannot have explicit constructors.

3. An object that does not have a reference variable is called anonymous object. It is not stored in a variable.

4. Java anonymous object creation is useful when it is not used more than once.


In this tutorial, we have covered all important points related to anonymous object with examples. Hope that you will have understood the usage of an anonymous object in Java program. In the next tutorial, we will understand types of classes in Java.
Thanks for reading!!!

⇐ Prev Next ⇒

Please share your love