A nested class is a class declared within another class. It’s a member of the enclosing class and so can be declared private, public, protected or default.

A nested class can be static, inner, local or anonymous. The following sections try to clarify these sometimes-confusing terms.

Static Nested Classes

The two key things you must know about static nested classes are:

  • They don’t have access to the non-static members of the enclosing class
  • They are behaviorally like a top-level class that has been nested in another top-level class for packaging convenience

The following is an example of a static nested class, including how you can create an object of such a class (lines 15 and 23):

Inner Classes (Non-Static Nested Classes)

Inner classes are the second category of nested classes. Again, there are two key things you must know about them:

  • They have access to the members of the enclosing class (even private)
  • Since they are associated with an instance (an object), they can’t define any static members themselves (except constant variables, i.e. primitive type or String, declared final and initialized with a compile-time constant expression)

There are two specialized types of inner classes:

  • Local classes
  • Anonymous classes

Local Classes

They are class declarations inside a block and:

  • They have access to local variables declared final
  • Inside static methods they can only refer to static members of the enclosing class

Anonymous Classes

They are expressions of two kinds, either implementing an interface (new InterfaceName(){ … }) or extending another class (new ClassName(args) { … }). In both cases:

  • They have access to local variables declared final
  • They can’t declare constructors

The following is an example of an anonymous class extending the EventHandler class:

 


Leave a Reply