What is an inner class in Java?
An inner class is a class defined within the body of another class or interface. Java has four distinct kinds, each with different scoping and access rules.
**Non-static inner class** (member inner class): defined at the class level without `static`. It has an implicit reference to the enclosing instance and can access all members of the outer class, including private ones. Because of the implicit reference, you need an outer instance to create one: `Outer.Inner i = outer.new Inner()`. The implicit outer reference also means these classes are a common source of memory leaks — they prevent GC of the outer instance.
**Static nested class**: declared with `static`. It does not hold a reference to the enclosing instance. It can only access static members of the outer class directly. It is instantiated as `new Outer.Nested()`. This is the preferred default when inner class access to instance state is not needed, precisely because there is no implicit reference and no leak risk.
**Local class**: defined inside a method body. It can access local variables of the enclosing method, but only if they are effectively final. Scope is limited to the method.
**Anonymous class**: a one-off, nameless class defined inline, typically as an argument or assignment. Common before Java 8 for event listeners and callbacks — largely superseded by lambda expressions for single-abstract-method interfaces.
The key design guidance: prefer static nested classes over non-static inner classes unless you genuinely need access to the enclosing instance's state. Non-static inner classes are the primary source of hard-to-diagnose memory leaks in Android and long-lived Java applications — the outer object cannot be GC'd as long as the inner object is alive.
All four types can access `private` members of the outer class through compiler-generated synthetic accessor methods.
Names and distinguishes at least three of the four types, correctly explaining the implicit outer reference in non-static inner classes.
Also covers the memory leak risk of non-static inner classes, the design guidance to prefer static nested, and the effectively-final requirement for local classes.
Reading the answer is step one. Explaining it unprompted — under interview pressure — is what actually matters. Get AI-graded feedback on your answer with follow-up probes on your weak points.
Get Graded — Free Assessment