Classes/Objects  «Prev  Next»
Lesson 8 Inner classes
ObjectiveDiscuss how inner classes are declared and used.

Inner classes

The release of JDK 1.1 introduced support for inner classes (and inner interfaces), which are classes (or interfaces) that are declared as a member of another class or interface. The following is an example of an inner class definition:

 class Outer {
  // Outer class body
  class Inner {
   // Inner class body

The Inner class (referred to as Outer.Inner) is defined within the context of the Outer class (referred to as simply Outer). Since inner classes are class members, they are allowed to have access modifiers[1] (public, protected, private, or package access). They may also be declared as abstract, final, or static.
Inner classes are also referred to as nested classes .
Nested class: A class that is declared as a member of another class or interface.

Non-static inner classes

An instance of a non-static inner class is associated with an enclosing scope[2] (for example, class, method, or block).
This enclosing scope is the instance of the outer class in which it is created.
Variables and methods that are declared in the outer class are accessible within the inner class.

Static inner classes

static inner classes differ from "regular inner classes" (non-static inner classes) in that they do not have an object instance as an enclosing scope. Instead, static inner classes have a static enclosing scope and are considered to be equivalent to a top-level class (and are referred to as top-level classes [3]). Static inner classes may access static variables that are defined in any enclosing classes.Since static inner classes are not associated with an object instance, they may only have static members. Likewise, a non-static inner class may not have static members. Multiple levels of inner classes are possible but are usually impractical.

[1]Access modifier: A modifier that is used to limit access to a class, class member, or constructor.
[2]Enclosing scope: The instance of an outer class in which an instance of an inner class is created.
[3]Top-level class: A class that is not nested or a static inner class.