Course contentsShow
← Java
Lesson 641 of 2,87015. Nested and Inner ClassesFree lesson

Anonymous Class Syntax

Learn the syntax: new Type() { body } for interfaces and new Class() { body } for extending classes.

Anonymous Class Syntax

What you'll learn: How to declare and instantiate an anonymous class inline using Java's special syntax.

The Core Idea

An anonymous class is a class without a name that you declare and instantiate in a single expression. Unlike local classes (which you declare and then instantiate separately), anonymous classes combine both steps using special syntax.

There are two forms, depending on whether you're implementing an interface or extending a class:

Syntax for Interfaces

new InterfaceName() { 
    // class body: methods, fields, etc.
}

Syntax for Classes

new ClassName() { 
    // class body: overridden methods, fields, etc.
}

Understanding the Pattern

The syntax looks like you're creating an instance with new, but immediately after the parentheses (where constructor arguments go), you add curly braces { } containing a class body. This creates a new, unnamed subclass on the spot and instantiates it.

For interfaces, you're creating a class that implements that interface. For classes, you're creating a subclass that extends the given class.

Think of It This Way

Imagine ordering a custom sandwich. Instead of giving it a name and adding it to the menu, you just describe exactly what you want right when you order: "I'll have a sandwich with these specific ingredients." Anonymous classes work the same way—you define the class exactly where you need it, without bothering to name it first.

Key Takeaway: Anonymous class syntax is new Type() { body } where Type can be an interface to implement or a class to extend, creating an unnamed class instance in one expression.