Anonymous Objects

Naveen AnamaneniUpdated · 4 min read
easyJava 25javaoopobjects

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

Used once, then unreachable
Anon.java▶ Try it
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());
    }
}
Output
505
java

How it works

  1. Line 9 creates a Bill object and calls total on it in the same expression. The object has no name.
  2. Line 10 does the same with a library class: a StringBuilder is created, reversed and printed.
  3. 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

PatternExample
Passing an object straight into a methodlist.add(new Ticket("Navika", 23));
One-off calculationsnew Scanner(line).nextInt()
Building and printingSystem.out.println(new StringBuilder("ab").reverse());
Chained buildersnew 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 objectAnonymous class (see "Anonymous Inner Class in Java")
What has no nameThe object (no variable)The class itself
Examplenew Bill().total(1, 2)new Runnable() { public void run() { ... } }
Defines new codeNoYes: 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

  1. Easy: Print the length of "Mysuru" using an anonymous String method call, new String("Mysuru").length(). Then explain why "Mysuru".length() is better.
  2. Harder: Add three anonymous Ticket objects straight into an ArrayList with add(new Ticket(...)), then print the list's size.

Quick check: Anonymous objects

4 questions
1What is an anonymous object?
2How many objects do new Bill().total(1, 2); new Bill().total(3, 4); create?
3What happens to an anonymous object after its expression finishes?
4In list.add(new Ticket("Navika", 23));, is the ticket lost after the call?

Key Takeaways

Was this tutorial helpful?

Lesson 97 of 482