Java Nested Class

928 views 3 minutes read
A+A-
Reset

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.

Example:

Test.java

package pack;

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

it will print 100 in output.

Leave a Reply

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More

Index

Adblock Detected

Please support us by disabling your AdBlocker extension from your browsers for our website.