«Back to Home

Core Java

Topics

Introduction Of Nested Class In Java

Nested Class
 
A class, which is declared inside the class or an interface is called as a nested class in Java.
 
If we use the nested classes to logically group of the classes and the interfaces in one place, it can be more readable, maintainable and can access all the members of the outer class (public, private and protected).
 
Syntax

class Java_Outer_class{
class Java_Inner_class{     // nested class
    }
}
 
Advantages of nested classes in Java are,

There are many advantages of the nested classes in Java. They are given below.
  1. Nested classes show a special type of relationship, it can access all the member of the outer class including private.

  2. Nested classes are mainly used to build up our program more readable and maintainable because it logically groups the classes and the interfaces in one place only.

  3. Nested classes require less code to write.
How to differentiation between nested class and inner class in Java

In Java, all the inner classes are a part of the nested class and non-static nested classes are called as inner classes.
 
Types of Nested classes
 
In Java, two types of nested classes are,
  • Non-static nested classes.

    These classes are the non-static members of a class.

  • Static nested classes.

    These classes are the static members of a class.

    69
The non-static nested classes are also called as the inner classes.
 
Inner class (non-static nested class)
  1. Member inner class

  2. Annomynous inner class

  3. Local inner class
Static nested class
  1. Member inner class

    This class is created within the class and outside the method.

  2. Anonymous inner class

    This class is created to implement an interface or extend the class. Its name is decided by the compiler.

  3. Local inner class

    This class is created within the method

  4. Static nested class

    This static class is created within the class

  5. Nested interface

    This interface created within the class or the interface
Summary
 
Thus, we learnt that a class, which is declared inside the class or an interface is called a nested class in Java and also learnt its types and advantage.