Open In App

Anonymous Object in Java

Last Updated : 03 Feb, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In Java, an anonymous object is an object that is created without giving it a name. Anonymous objects are often used to create objects on the fly and pass them as arguments to methods. Here is an example of how to create and use an anonymous object in Java.

Example:

Java




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

In this example, we create an anonymous object of the Person class and call its display method. The anonymous object is created using the new keyword and is immediately passed to the display method, without giving it a name. Anonymous objects are often used in combination with inner classes, anonymous classes, and lambda expressions. For example, here is how you might use an anonymous object with an inner class:

Example:

Java




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 InnerClass

The OuterClass defines an inner class called InnerClass. The InnerClass has a single method, display, which prints a message to the console. The Main class is defined as the entry point for the program. It contains a main method, which is the starting point for the program. Inside the main method, we create an anonymous object of the InnerClass using the new keyword and the OuterClass.new InnerClass() syntax. This creates a new instance of the InnerClass and assigns it to an anonymous object. We then call the display method on the anonymous object using the dot notation (e.g. obj.display()). This calls the display method on the anonymous object and prints the message “Inside InnerClass” to the console.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads