Java - Inner Class Inner Class

What Is an Inner Class?

A class can be declared within another class.

This type of class is called an inner class.

If the class declared within another class is explicitly or implicitly declared static, it is called a nested class, not an inner class.

The class that contains the inner class is called an enclosing class or an outer class.

Example


class Outer {
       public class Inner {
               // Members of the Inner class go here
       }
       // Other members of the Outer class go here
}

The Outer class is a top-level class.

The Inner class is an inner class.

It is a member of the Outer class.

The Outer class is the enclosing class for the Inner class.

An inner class can be the enclosing class for another inner class.

Note

There are no limits on the levels of nesting of inner classes.

You must have an instance of the enclosing class before you can create an instance of an inner class.

An inner class has full access to all the members, including private members, of its enclosing class.

Inner Class Type

There are three types of inner classes.

The type of inner class depends on the location and the way it is declared.

  • Member inner class
  • Local inner class
  • Anonymous inner class

Related Topics