Member Classes
Home ] Up ] Static Member Classes ] [ Member Classes ] Local Classes ] Anonymous Classes ]

 

Example
Running the Example

 

Next, we have (non-static) member classes.

Such a class is a member of an enclosing class, but not defined as static.

This is totally analogous to an instance method or instance field -- the nested class becomes an instance member of the enclosing class.

Just like static member classes, such a class is enclosed within the namespace of the enclosing class, so references to it must be qualified.

Note: An instance of a member class is always associated with an instance of the enclosing class.
Here is the main advantage of member classes:

The code of a member class has access to all the fields and methods (static or non-static, private, whatever) of its enclosing class instance.

Note that Interfaces may not be defined as non-static members.

So, I'm going to take advantage of this behavior and change our Enumerator class into a member class of Stack...

Note:

  • We can remove the argument to Enumerator's constructor, because the member class is internally associated with the instance of its enclosing class.
  • The member class can directly access its enclosing class' members, including private members.
  • Member classes can be nested within member classes.
  • There is potential ambiguity when a member class instance accesses the containing class instance. When you wish to use this, to which instance does it refer?

    To resolve this problem, member classes introduce new syntax for this, new and super:

Stack.this
Enumerator.this
Stack stack = new Stack(20);
Stack.Enumerator en = stack.new Enumerator()	
	// specifies containing instance
stack.super()
	// used when top-level class extends a
	// member class (esoteric)
  • A member class may not have the same name as any containing class or package
  • A member class may not contain any static members

 

This page was last modified on 02 October, 2007