Home ProgrammingJava Java Nested Class

Java Nested Class

by Log Raj Bhatt
0 comment 495 views

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 privatestatic and non static members of outer class.
  • Member nested class cannot have static members therefor we can not define main method inside normal inner class.
  • this inside inner class represent the object of inner class. To access current object of outer class we can use Outer.this.



package pack;

//Outer class
public class Test {
	private int x=100;
	class InnerClass{	// Inner class
		void display() {
	public static void main(String[] args) {
		Test t=new Test();
		// Creating objects of inner class
		Test.InnerClass ti=t.new InnerClass();

it will print 100 in output.

0 comment

Leave a Reply

Do NOT follow this link or you will be banned from the site!