What is inner classes in java?

Inner class is defined inside another class or interface. It is mainly used to logically relate classes and interfaces in one place.It makes code more readable and maintainable.

There are two kinds of inner classes.

  • Static Classes
  • Non-static classes

It can access all the members of outer class including private data members and methods.

Non-Static inner class

A non-static nested class has full access to the members of the class within which it is nested.You need reference of outer class to create instance of inner class.


class OuterClass{

private int val=10;

public void display(){

System.out.println("Outer class method invoked");


class InnerClass{

public void show(){


System.out.println("Value of val"+val);






public class InnerTest{

public static void main(String args[]){

//To instantiate the non-static inner class you need to instantiate the outer class

OuterClass outer= new OuterClass();

OuterClass.InnerClass inner= outer.new InnerClass();



Static inner class

A static class created inside a class is called static nested class. It cannot access non-static data members and methods. Its instance can be obtained without the instance of outer class i.e its instance can be obtained by outer class name.

    package com.startwithjava;
    class TestOuter{  
      static int num=10;  
      static class Inner{  
       public void display(){System.out.println("Num="+num);}  
      public static void main(String args[]){  
      TestOuter.Inner obj=new TestOuter.Inner();  

Leave a Reply