ProgrammingJava Developer

Tell us about the key features of working with anonymous and nested classes in Java, as well as the pitfalls of their usage.

Pass interviews with Hintsage AI assistant

Answer.

Nested classes are classes defined within another class. They can be:

  • Static nested classes; they do not have access to the non-static members of the outer class without an instance.
  • Inner classes; non-static nested classes; they have access to all members of the outer class.
  • Anonymous classes; unnamed inner classes, typically declared and created at the point of use, often when working with interfaces/abstract classes.

Example of an anonymous class:

Button b = new Button(); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // action on click } });

Features:

  • Anonymous classes can only access final (effectively final) variables from the enclosing scope.
  • Each instance of an inner class implicitly holds a reference to the instance of the outer class.
  • Depending on the type (static/inner), memory leaks or unexpected dependencies may arise.

Trick question.

Can a non-static inner class contain static methods or variables?

Answer: No, it cannot, except for constants (static final). Only a static nested class can have static members.

Example (error):

class Outer { class Inner { static int x = 10; // Compilation error! } }

It would be correct like this:

class Outer { static class StaticNested { static int x = 10; // OK } }

Examples of real errors due to misunderstanding the nuances of the topic.


Story

In an Android app, an inner class was used as an event handler. The handler was stored in a static field and held an implicit reference to the Activity, which caused a memory leak when it was destroyed, leading to the app "leaking" up to an OutOfMemoryError.


Story

In one of the microservices, anonymous classes were used that referenced external iterator variables. After refactoring, the variables ceased to be effectively final, and the code stopped compiling — the developers searched for the reason for a long time until they remembered this limitation.


Story

A library used static variables inside an inner class, thinking it was common practice. In newer versions of the JDK, the project stopped compiling as the standards became stricter in following the restrictions. An urgent architectural redesign was needed.