Logo Data Structures and Algorithms with Object-Oriented Design Patterns in Java
next up previous contents index

Static Inner Classes

Consider the following Java code fragment:

public class A
{
    int y;

    public static class B
    {
	int x;

	void f () {}
    }
}
This fragment defines the class A which contains an static inner class B.

A static inner class behaves like any ``outer'' class. It may contain methods and fields, and it may be instantiated like this:

A.B object = new A.B ();
This statement creates an new instance of the inner class B. Given such an instance, we can invoke the f method in the usual way:
object.f();

Note, it is not necessarily the case that an instance of the outer class A exists even when we have created an instance of the inner class. Similarly, instantiating the outer class A does not create any instances of the inner class B.

The methods of a static inner class may access all the members (fields or methods) of the inner class but they can access only static members (fields or methods) of the outer class. Thus, f can access the field x, but it cannot access the field y.


next up previous contents index

Bruno Copyright © 1998 by Bruno R. Preiss, P.Eng. All rights reserved.