info@tutsfinder.in



Java Inner Class

Inner class also known as nested classes which are define inside another class.

Inner classes are non-static nested classes.

Inner classes are able to access the data of outer class including private data members and methods.

It helps in to grouping of classes that are related to each other.

Increases readability and maintainability of code.

Types of Inner class –

1. Nested Inner Class

2. Local Inner Class

3. Anonymous Inner Class


Nested Inner class can access other instance variables of the outer class, even if they are declared as private.

Class created inside a method is known as local inner class. If you want to invoke the method of local inner class, you must instantiate this class inside the method.

A class that have no name is known as Anonymous Inner class. It is created in two ways –

1. Class

2. interface


Program to show how we can acces the data of inner class.


class Outer {
   int num;
   
   private class Inner {		// inner class
      public void show() {
         System.out.println("This is an inner class");
      }
   }
   
   void showInner() {		//access inner class method from method in outer class
      Inner in = new Inner();
      in.show();
   }
}
   
public class InnerClassDemo {

   public static void main(String[] args) {
      
      Outer out = new Outer();
      
      
      out.showInner();
   }
}
	


Here, Outer is an outer class and Inner is an inner class and show is the method inside inner class.

Output:

This is an inner class