CIS 35A: Introduction to Java Programming

Home | Green Sheet | Lectures | Assignments | FAQ | Grades

Packages

Packages
Related classes
Nested classes

An introduction to nested classes

  • Java has provided support for nested classes since version 1.1.
  • When you nest classes, the outer class must be declared public and must have the same name as the file name of the class.
  • Within an outer class, you can nest inner classes and static inner classes. Since the inner classes are members of the outer class, they are sometimes called member classes.
  • A class can also be nested inside a method or any other type of block. These types of classes are sometimes called local classes.

Two classes nested within another class

public class OuterClassName
{
    // can contain instance variables and methods
    // can contain static variables and methods

    class InnerClassName
    {
        // can contain instance variables and methods
        // can't contain static variables or methods
        // can access all variables and methods of
        //     OuterClass
    }

    static class StaticInnerClassName
    {
        // can contain instance variables and methods
        // can contain static variables and methods
        // can access static data from OuterClass
        // can't access instance variables or methods from OuterClass
    }
}

The class files generated for the preceding class

OuterClassName.class
OuterClassName$InnerClassName.class
OuterClassName$StaticInnerClassName.class

A class nested within a method

public class ClassName
{
    // code for the outer class

    public void methodName()
    {
        class InnerClassName
        {
            // code for the inner class
        }

        // code for the method
    }
}

The class files generated for this class

ClassName.class
ClassName$InnerClassName.class
Previous | Code more than one class | Nested classes | Next