Nearby lessons
47 of 125Java - Anonymous Inner Class
📌 What You Will Learn
- What an inner class is and why we need it
- The four types: member, static nested, local, anonymous
- How to create objects of inner classes
- Where anonymous inner classes are used in real projects
Anonymous Inner Class is a core concept of the Java language. This lesson explains Anonymous Inner Class with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.
Anonymous Inner Class
An anonymous class has no name. It is created at the same place where it is used, usually to give a quick implementation of an interface or an abstract class. It is very common in GUI event handling and in modern code with functional interfaces.
Trainer's Note: Updated knowledge: In modern Java (Java 8+), the same job is done more simply with a lambda expression: Greeting g = () -> System.out.println("Hello"); We will study lambdas in the Java 8 chapter. But you will still meet anonymous classes in older code and in GUI programs, so understand the idea well.
In simple words: An anonymous inner class is a one-time class with no name. You write the whole implementation right where you need it, usually to override one small behaviour.
Example01
📝 Key Takeaways
- Inner class = a class declared inside another class.
- Member inner class needs an outer object: outer.new Inner().
- Static nested class is created with Outer.Nested, no outer object needed.
- Local inner class lives inside a method.
- Anonymous inner class has no name and is used for one-time implementations.
- Modern code prefers lambda expressions for one-method interfaces, but anonymous classes still appear in real projects.
🧠 Test Your Knowledge
2 QuestionsProgress: 0 / 2