bugl
bugl
HomeLearnPatternsPathsSearch
HomeLearnPatternsPathsSearch

Loading lesson path

Learn/Java/Java Classes
Java•Java Classes

Java Anonymous Class

Flash cards

Review the key moves

1/4
Core idea

What is the main idea behind Java Anonymous Class?

Lesson checks

Practice each idea before moving on

Short Mimo-style checks built from this lesson's code, terms, and sequence.

1Quick choice

Which statement best captures the main point of this lesson?

2Fill blank

Complete the missing token from the example code.

// Normal ___ class Animal { public void makeSound() { System.out.println("Animal sound");
3Order

Put the learning moves in the order that makes the concept easiest to apply.

You often use anonymous classes to override methods of an existing class or interface, without writing a separate class file.
An anonymous class is a class without a name.
Anonymous Class from an Interface

Anonymous Class

An anonymous class is a class without a name. It is created and used at the same time.

You often use anonymous classes to override methods of an existing class or interface, without writing a separate class file.

Here, we create an anonymous class that extends another class and overrides its method:

Runnable example

// Normal class class Animal { public void makeSound() { System.out.println("Animal sound");
}
}
public class Main {
  public static void main(String[] args) {
    // Anonymous class that overrides makeSound() Animal myAnimal = new Animal() { public void makeSound() { System.out.println("Woof woof");
  }
}; // semicolon is required to end the line of code that creates the object
myAnimal.makeSound();
}
}

Anonymous Class from an Interface

You can also use an anonymous class to implement an interface on the fly:

Runnable example

// Interface interface Greeting { void sayHello();
}
public class Main {
  public static void main(String[] args) {
    // Anonymous class that implements Greeting Greeting greet = new Greeting() { public void sayHello() { System.out.println("Hello, World!");
  }
};
greet.sayHello();
}
}

Use anonymous classes when you need to create a short class for one-time use. For example:

  • Overriding a method without creating a new subclass
  • Implementing an interface quickly
  • Passing small pieces of behavior as objects

Previous

Java Interface

Next

Java Enums