Java Nested and Inner Class

Nested classes 

A class declared inside any other class/interface is called a nested class. You may have any number of levels of nesting (i.e. deep nesting is possible) but nesting up to level two is recommended. A nested class can be declared static or non-static. To declare a static nested class, use the modifier static. A nested class can extend some other class and can itself be extended.

Example:

class Outer { //A top level class - Outer is the enclosing (outer) class of Nested1 and Nested2
 
   //..code
   public static void main(String[] args) {
       //..code
   }
 
   class Nested1 { // 1st nested class - is the enclosing (outer) class of Nested2 [it may or may not static]
 
       //..code
       class Nested2 { //2nd nested class [it may or may not static]
 
           //..code
 
       }// Nested2
 
       //..code
 
   }//Nested1
 
   //..code
}//Outer

Explanation:

After compilation, Outer.class,  Outer$Nested1.class and Outer$Nested1$Nested2.class files are created.

JVM is not aware of the nesting of the classes. A nested class can be static or non-static.

Inner classes

A non-static nested class is called an inner class. Inner classes cannot have static members. They cannot have final fields. From the code of the inner class, it is possible to access directly (without using objects of the outer class) members of the outer class, including the private members. From the code of the outer class direct access to the members of the inner class is not possible, but it is possible to do so using an object of the inner class. An inner class is a member of its enclosing class and so it can be declared public, private, or protected.

Code:

Java Code

class Outer { //an outer class
   int m;
   double d;
 
   Outer(int m, double d) {
       this.m = m;
       this.d = d;
   }
 
   class Inner { //an inner class
       int mm;
       double dd;
 
       Inner(int mm, double dd) {
           this.mm = mm;
           this.dd = dd;
       }
 
       void show() { // a method of Inner
           System.out.println(m); //direct access of m at Outer
           display();
       }
   }//Inner
 
   void display() { // a method of Outer
       //System.out.println(mm);
       //show( ); error – outer class cannot directly access members of inner class
       Inner inner = new Inner(10, 10.4);
       inner.show();
   }
 
   public static void main(String[] args) {
 
   }
}

Explanation:

After compilation the class files created are Outer.class and Outer$Inner.class

Special thanks to Jay S. Prajapati for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this articleIf you want to suggest any improvement/correction in this article please mail us at [email protected]