Nested Classes in Java

Java 8Object Oriented ProgrammingProgramming

Writing a class within another is allowed in Java. The class written within is called the nested class, and the class that holds the inner class is called the outer class. Nested classes are divided into two types −

  • Non-static nested classes (Inner Classes) − These are the non-static members of a class.

  • Static nested classes − These are the static members of a class.

Following are the types of Nested classes in Java −

Non-static nested classes (Inner Classes)

Inner classes are a security mechanism in Java. We know a class cannot be associated with the access modifier private, but if we have the class as a member of other class, then the inner class can be made private. And this is also used to access the private members of a class.

Let us see an example −

Example

class Outer_Demo {
   int num;
   // inner class
   private class Inner_Demo {
      public void print() {
         System.out.println("This is an inner class");
      }
   }
   // Accessing he inner class from the method within
   void display_Inner() {
      Inner_Demo inner = new Inner_Demo();
      inner.print();
   }
}
public class My_class {
   public static void main(String args[]) {
      // Instantiating the outer class
      Outer_Demo outer = new Outer_Demo();
      // Accessing the display_Inner() method.
      outer.display_Inner();
   }
}

Output

This is an inner class.

Static Nested Classes

A static inner class is a nested class which is a static member of the outer class. It can be accessed without instantiating the outer class, using other static members. Just like static members, a static nested class does not have access to the instance variables and methods of the outer class.

Let us see an example −

Example

public class Outer {
   static class Nested_Demo {
      public void my_method() {
         System.out.println("This is my nested class");
      }
   }
   public static void main(String args[]) {
      Outer.Nested_Demo nested = new Outer.Nested_Demo();
      nested.my_method();
   }
}

Output

This is my nested class
raja
Published on 20-Sep-2019 11:08:35
Advertisements