Anonymous Inner class — Java Technical Interview Questions & Answers
Anonymous Inner class
Anonymous Inner class
- Anonymous Inner class: inner/nested classes live inside another class. Anonymous Inner class is useful for helpers tightly coupled to the outer type.
- Anonymous Inner class: anonymous class = one-off implementation.
- Anonymous Inner class: static nested class does not need outer instance.
- Write one tiny example for Anonymous Inner class. Compile, print one result, and say the output out loud before you type.
- Use Anonymous Inner class only when the problem needs it. Don’t force it into every program. Know one beginner trap.
- Let's take this on the board with one tiny Main class — no extra files. Anonymous Inner class — static nested Pair groups two ints with the outer Main type. Start from main, go line by line, and stop at each print. That output is the proof for Anonymous Inner class.
Technical Interview Tip: Give one real use: event listener / Comparator.
Code Examples for Anonymous Inner class
Example
public class Main {
static class Pair {
final int a, b;
Pair(int a, int b) { this.a = a; this.b = b; }
}
public static void main(String[] args) {
Pair p = new Pair(2, 3);
System.out.println(p.a + p.b);
}
}Anonymous Inner class — static nested Pair groups two ints with the outer Main type.
How to Explain Anonymous Inner class to an Interviewer
What is Anonymous Inner class?
Anonymous Inner class is a Java idea you should explain with one small example. Know the keyword / API used for Anonymous Inner class. Type a tiny Main and print one result. For Anonymous Inner class, say the output before you code.
Why do we use Anonymous Inner class in Java?
Makes the program clearer or safer Anonymous Inner class is a Java idea you should explain with one small example.
Write one small example of Anonymous Inner class.
Show syntax Say what prints
What mistake do beginners make with Anonymous Inner class?
Only the name, no example Anonymous Inner class — only memorising the heading. No example, no trap.
Where is Anonymous Inner class used in a real program?
Day-to-day Java code