SHARE
Java Nested Class Example on Kanye West

In Java we can write a class inside another class. Java Nested Class is the class defined in another class. Among these two, outer one is outer class and another class which is inside outer class is inner class Therefore outer class contains definitions of inner classes.

Advantages of Java Nested class

  • Better logical grouping of related code
  • It increases the encapsulation by hiding a class from outside code.
  • It can lead to more readable and maintainable code.

Types of Nested Class :

There are two types of nested classes

  • Non-Static nested classes
  • Static nested classes

Non-static nested classes

  • Non-static classes are also called inner classes.
  • A class defined inside another class or interface is inner class.
  • Inner classes have access to all other members of the enclosing class.
  • We can use private or protected access modifier with inner classes so that we can restrict the access of these nested classes.
  • To instantiate inner class, you first need to instantiate outer class.

Non-static nested classes may be inside method of class, or these may be outside any method or with new operator. Based on where you define inner class, there are 3 types of inner classes.

  • Member nested class
  • Local nested class
  • Anonymous nested classes

Here we only describe about Member nested class.

Member Nested Class

  • A non-static class inside the class but outside a method is member inner class of that class.
  • Java compiler create two class files one for outer class and another for inner class.
  • Instance of inner class is defined inside the instance of outer object means that Object of outer class is necessary to create object of inner class.
  • But inside other member method of outer class we can simply instantiate inner class.
  • Instance inner class can access private staticand non static members of outer class.
  • Member nested class cannot have static members therefor we can not define main method inside normal inner class.
  • thisinside inner class represent the object of inner class. To access current object of outer class we can use Outer.this.

Example:

Test.java

it will print 100 in output.

Facebook Comments

comments