Nested Types

  • A nested type has access to the member variables and methods of its enclosing type.

  • It has intimate access to the internals of its enclosing type, thus bending the rules of “encapsulation”.

  • They are tied to their enclosing type and usually cannot exist independently on their own.

  • Alternatively, it is required for a very specific reason. Being tightly localised, they are part of the enclosing implementation detail.

  • These types can be nested in the following ways:

    • Static member types

    • Non-static member classes

    • Local classes

    • Anonymous classes

Static Member Types

  • A nested static member type is not associated with any instance of the containing class, thus it does not have a this object reference.

  • It can only access static members of the containing type (class or interface). The containing type can also access all members of the static member.

  • Nested interfaces, enums and annotations are implicity static, regardless of whether they have a static keyword against them.

Non-static member classes

  • A non-static member class is analogous to an instance field or instance method of the containing class instance.

  • Only classes can be nested non-static members of a containing class.

  • An instance of a non-static nested member class is always associated with the instance of the encolosing type.

  • The non-static member class has access to all static and non-static fields and methods of its enclosing type.