Inner Classes / Nested Classes overview

//Inner Classes / Nested Classes overview
  1. What is Inner Class / Nested Class?

  2. Types of Inner Classes

  3. Why use inner classes?

 

What is inner class :

    The Java programming language allows you to define a class within another class. Such a class is called nested class. The relationship between outer class and inner class is not IS-A relationship and it is Has-A relationship.

    Interfaces also can be nested. Below are some possible inner classes

    Example 1:
    //outer class
    class OuterClass {
    //inner class
    class InnerClass {
    }
    }
    Example 2:
    //outer interface
    interface OuterInterface {
    //inner interface
    interface InnerInterface {
    }
    }
    Example 3:
    //outer class
    class OuterClass {
    //inner interface
    interface InnerInterface {
    }
    }
    Example 4:
    //outer interface
    interface OuterInteerface {
    //inner class
    class InnerClass {
    }
    }
    Example 5:
    //outer class
    class OuterClass {
    //Static inner class
    static class StaticInnerClass {
    }
    }

    Types of Nested / Inner Classes:

    Based on the purpose and position of declaration all inner classes are divided into 4 types.

    1. Normal or Regular inner classes (Non static)
    2. Local Classes
    3. Anonymous inner classes
    4. Static nested classes.

    Why use inner classes ?

    • It is a way of logically grouping classes that are only used in one place.
    • It increases encapsulation.
    • It can lead to more readable and maintainable code.
    • Without existing one type of object if there is no chance of existing another type of object then we can go for inner classes.