Java Tutorial
Operators
Flow Control
String
Number and Date
Built-in Classes
Array
Class and Object
Inheritance and Polymorphism
Exception Handling
Collections, Generics and Enumerations
Reflection
Input/Output Stream
Annotation
In Java, an anonymous object is an object created without assigning it to any reference variable. Anonymous objects are often used when you need to use an object only once, and there is no need to reference it later in your code. In this tutorial, you will learn how to create and use anonymous objects in Java.
First, let's define a simple class called Printer
:
public class Printer { public void printMessage(String message) { System.out.println("Message: " + message); } }
Now, let's create an anonymous object of the Printer
class and call the printMessage
method directly, without assigning the object to any reference variable:
public class AnonymousObjectDemo { public static void main(String[] args) { // Create an anonymous object and call the printMessage method new Printer().printMessage("Hello from an anonymous object!"); } }
In this example, we create an anonymous object of the Printer
class and directly call the printMessage
method on it. Since the object is not assigned to any reference variable, it cannot be reused later in the code.
Compile and run the AnonymousObjectDemo
class, and you should see the following output:
Message: Hello from an anonymous object!
This tutorial demonstrates how to create and use anonymous objects in Java. Anonymous objects can be useful in cases where you need to use an object only once and do not need to reference it later in your code. However, keep in mind that using anonymous objects can make your code harder to read and maintain, especially when dealing with more complex logic.
Java Anonymous Object Creation: Anonymous objects are objects created without assigning them to a variable. They are useful for one-time use.
new MyClass().doSomething();
Creating Anonymous Objects in Java: Anonymous objects are instances of a class created on-the-fly without assigning them to a reference variable.
new Rectangle(5, 10).calculateArea();
Java Anonymous Object vs Named Object: Anonymous objects are unnamed and used for one-time operations, while named objects are assigned to variables for reuse.
Rectangle namedObj = new Rectangle(5, 10); namedObj.calculateArea();
Anonymous Object Usage in Java: Anonymous objects are commonly used for quick, short-term operations without the need for reuse.
int result = new Calculator().add(5, 7);
Java Anonymous Object and Method Chaining: Anonymous objects can be used for method chaining, where multiple methods are called in sequence on the same object.
new StringBuilder().append("Hello").append(" ").append("World").toString();
Anonymous Object Creation for Method Arguments in Java: Anonymous objects are often used as arguments for methods when their usage is limited to a specific method call.
printMessage(new Message("Hello, World!"));
Java Anonymous Object Initialization: Anonymous objects can be initialized with constructor arguments during creation.
new Point(3, 7).printCoordinates();
Java Anonymous Object as Method Return Type: Methods can return anonymous objects when a temporary result needs to be generated.
public Rectangle createRectangle(int width, int height) { return new Rectangle(width, height); }
Java Anonymous Object and Functional Programming: Anonymous objects can be used in functional programming constructs, especially when dealing with one-time operations.
List<String> uppercaseNames = names.stream() .map(name -> new String(name).toUpperCase()) .collect(Collectors.toList());
Anonymous Object in Java Collections: Anonymous objects can be directly used in collections for short-term data representation.
List<Point> points = new ArrayList<>(); points.add(new Point(1, 2));
Java Anonymous Object and Immutability: Anonymous objects can be used to represent immutable data structures when their state doesn't change after creation.
String uppercase = new String("hello").toUpperCase();
Creating Anonymous Objects for Testing in Java: Anonymous objects are convenient for testing when you need quick instances of objects to check specific behaviors.
assertEqual(42, new Calculator().add(20, 22));