MJ #20: Anonymous Object in Java

In Java, an anonymous object refers to an object that is created without explicitly assigning it to a variable. Instead, it is used for a single, immediate purpose and is not stored in a named reference variable. Anonymous objects are typically used when you need an object to perform a specific action or method call, and you don’t need to reuse the object later in your code.

Here’s an example of creating and using an anonymous object:

package com.sarthak.concept.anonymousObject;

public class Animal {

    public void showAnimal(){
        System.out.println("I am Lion");
    }
}
package com.sarthak.concept.anonymousObject;

public class AnimalDemo {
    public static void main(String[] args) {

        //Anonymous Object
        new Animal().showAnimal();
    }
}

Anonymous objects are useful in situations where you need a temporary object to perform a specific task, and you don’t want to clutter your code with unnecessary variable declarations. However, they should be used judiciously, as they can make your code less readable if overused.

Leave a comment