An object which has no reference variable is called an anonymous object in Java. Anonymous means nameless.  If you want to create only one object in a class then the anonymous object is a good approach.

Declaration of Anonymous object in Java

The syntax to create an anonymous object in Java is given below.
Syntax
       new Class_name();
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 you can write code like this:
       new Student().display();

We can also pass the parameter to the calling method like this:
       new Student().display("Shubh", 25);

Let's create a program where we will implement all these concepts in a program.
Program source code 1:
    package anonymousObject; public class Multiplication { // Declare the instance variables int a; int b; int c; int d; // Declare the parameterize constructor and initialize the parameters. 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 and initialize parameters. 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 the anonymous object and pass the values to the constructor and calling method. new Multiplication(25,25).multiply(10, 20); // We can also pass the different value 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 make another program where we will create an anonymous object and calculate area and perimeter of square by passing different values to constructor and method. 


Program source code 2:
    package anonymousObject; public class Calculation { // Declare instance variable. int a; // Declaration of one parameter constructor. Calculation(int p){ a=p; } // Declaration of 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 object. 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
Final words
Hope that this tutorial has covered almost all important points related to anonymous object in java. I hope that you will have understood this simple topic and enjoyed it.
Thanks for reading!
Next ➤ Data Types in Java

⏪ Prev Next ⏩