Anonymous Objects
A paper cup at a tea stall is used once and thrown away; nobody writes their name on it. Some objects are like that: you need them for one call and never again. An anonymous object is created with new and used straight away, without storing it in a variable. It's a small idea, but you'll see it all over real Java code.
Create, Use, Forget
public class Anon {
static class Bill {
int total(int a, int b) {
return a + b;
}
}
public static void main(String[] args) {
System.out.println(new Bill().total(340, 165));
System.out.println(new StringBuilder("avaj").reverse());
}
}505
javaHow it works
- Line 9 creates a
Billobject and callstotalon it in the same expression. The object has no name. - Line 10 does the same with a library class: a
StringBuilderis created, reversed and printed. - After each line, nothing refers to those objects, so they're unreachable and the garbage collector can free them.
Try it yourself: call new Bill().total(10, 20) twice. How many Bill objects did that create?
Where You'll See Them
| Pattern | Example |
|---|---|
| Passing an object straight into a method | list.add(new Ticket("Navika", 23)); |
| One-off calculations | new Scanner(line).nextInt() |
| Building and printing | System.out.println(new StringBuilder("ab").reverse()); |
| Chained builders | new StringBuilder().append("Rs. ").append(450).toString() |
The first row is the most common: the object isn't stored in a local variable, because the list now holds the reference.
Not the Same as an Anonymous Class
| Anonymous object | Anonymous class (see "Anonymous Inner Class in Java") | |
|---|---|---|
| What has no name | The object (no variable) | The class itself |
| Example | new Bill().total(1, 2) | new Runnable() { public void run() { ... } } |
| Defines new code | No | Yes: a one-off class body in braces |
Common Mistakes
Expecting to use it again. Two new Bill() expressions make two different objects; changes to one aren't seen in the other.
Setting fields on it. new Ticket().berth = 23; compiles, but the object is lost immediately; the assignment is wasted.
Using it where a resource must be closed. new Scanner(file).nextLine() never closes the file; use a variable and try-with-resources (covered with exceptions, later in the course).
Practice
- Easy: Print the length of
"Mysuru"using an anonymousStringmethod call,new String("Mysuru").length(). Then explain why"Mysuru".length()is better. - Harder: Add three anonymous
Ticketobjects straight into anArrayListwithadd(new Ticket(...)), then print the list's size.
Key Takeaways
Was this tutorial helpful?