Nested classes are classes defined within another class. They can be:
Example of an anonymous class:
Button b = new Button(); b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // action on click } });
Features:
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 } }
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.