Static Nested Class — Java Technical Interview Questions & Answers
Static Nested Class
Static Nested Class
- Static Nested Class: inner/nested classes live inside another class. Static Nested Class is useful for helpers tightly coupled to the outer type.
- Static Nested Class: anonymous class = one-off implementation.
- Static Nested Class: static nested class does not need outer instance.
- Write one tiny example for Static Nested Class. Compile, print one result, and say the output out loud before you type.
- Use Static Nested 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. Static Nested 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 Static Nested Class.
Technical Interview Tip: Give one real use: event listener / Comparator.
Code Examples for Static Nested 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);
}
}Static Nested Class — static nested Pair groups two ints with the outer Main type.
How to Explain Static Nested Class to an Interviewer
What is Static Nested Class?
Static Nested Class is a Java idea you should explain with one small example. Know the keyword / API used for Static Nested Class. Type a tiny Main and print one result. For Static Nested Class, say the output before you code.
Why do we use Static Nested Class in Java?
Makes the program clearer or safer Static Nested Class is a Java idea you should explain with one small example.
Write one small example of Static Nested Class.
Show syntax Say what prints
What mistake do beginners make with Static Nested Class?
Only the name, no example Static Nested Class — only memorising the heading. No example, no trap.
Where is Static Nested Class used in a real program?
Day-to-day Java code