Flash cards
Review the key moves
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.
Which statement best captures the main point of this lesson?
Complete the missing token from the example code.
// Normal ___ class Animal { public void makeSound() { System.out.println("Animal sound");Put the learning moves in the order that makes the concept easiest to apply.
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