Interview Q&A · Java · 6 questions in this topic

Nested and Inner Classes — Java Interview Q&A

All Java topics

How Java nests one class inside another, and when to choose a static nested class versus an inner class. Part of Nested & Inner Classes · 294 questions in the Java bank.

What are nested classes?

Answer

A nested class is a class declared inside another class so the two stay logically together. Java divides nested classes into static nested classes and inner (non-static nested) classes. The static form needs no outer instance and is mainly namespacing plus encapsulation, while the inner form is bound to an outer instance and can use its state.

Key points

  1. 1A nested class is a member of its outer class, just like a field or method.
  2. 2Static nested class: declared with static, usable without an outer object.
  3. 3Inner class: no static modifier, tied to one outer instance.
  4. 4Nesting improves encapsulation by hiding helpers that no other class needs.

What are inner (non-static nested) classes?

Answer

An inner class is a nested class without the static modifier, so every instance belongs to an instance of the outer class. Because of that link it can directly read the outer object fields and methods, including private ones. Java has three kinds of inner class: member inner classes, local inner classes, and anonymous inner classes.

Key points

  1. 1Each inner object holds a hidden reference to its outer object.
  2. 2Member inner class: declared at class level without static.
  3. 3Local inner class: declared inside a method or block.
  4. 4Anonymous inner class: declared and instantiated in one expression with no name.

Why use nested classes?

Answer

Nested classes group a helper type with the only class that uses it instead of polluting the package with a tiny top-level class. They strengthen encapsulation because an inner class can use private outer members while staying hidden from the rest of the program. They also improve readability by placing related code together, and they let you hide an implementation such as a button event handler behind the class it serves.

Key points

  1. 1Grouping: keeps a one-use helper next to the class that needs it.
  2. 2Encapsulation: inner code can touch private outer state without exposing it.
  3. 3Readability: less navigation between tiny top-level files.
  4. 4Hiding: event handlers and iterators can stay private implementation details.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits