Nested Classes

Java allows classes to be nested inside another class. These are called nested classes.

Why use Nested Classes?

  1. Nested classes are used to logically group classes that are used in one place. Good examples are utility classes.
  2. Nested classes can increase encapsulation. Nested classes have access to private fields of the class. Instead of exposing the class fields to other class, the class can be nested and there the parents class fields can be declared private.
  3. Nested classes can result in clean and maintainable code by defining classes in places where the code should will be used.

Static Nested Classes

Static nested classed are defined with the static keyword.

Defining Static Nested Class

Accessing Static Nested Inner Class

The static nested inner class is accessed in the same way as other static members of the class.

OuterClass.NestedInner nestedInner = new OuterClass.NestedInner();

The nested static class will not have access to the non-static member variables. It accesses the outer class member variable just like any other class. The nesting is just for logical organisation.

Inner Classes

An inner class is a class defined inside another class as a member of the class.

The inner class have access to the outer class fields and methods. An instance of an inner class can only exists within an object of the outer class.

Defining inner class

public class OuterClass {
    class InnerClass
    {
      //code for the inner class here
      //inner class have access to OuterClass fields and methods
    }
}

Instantiating an inner class

The inner class can be used outside the outer class. To use it outside the outer class, the outer class needs to be instantiated first, then the inner class can be instantiated.

OuterClass outerClass = new OuterClass();
//we first need an object of the OuterClass to create the InnerClass object
OuterClass.InnerClass innerClass = outerClass.new InnerClass();

Shadowing

If the outer class defines a similar field as in the inner class, the outer class field will be shadowed. To access it you will need to fully qualify it.

public class OuterClass {
    int shadowedField = 5;
    class InnerClass
    {
        int shadowedField = 10;
        public InnerClass() {
        }

        void test(){
            //refer to the InnerClass shadowedField field
            shadowedField = shadowedField + 5;
            //to refer to the OuterClass shadowedField, we have to qualify it
            //use OuterClass.this.shadowedField
            shadowedField = OuterClass.this.shadowedField;
        }
    }
}

results matching ""

    No results matching ""