Nested Class and its necessity with example

Author posted by Jitendra on Posted on under category Categories JAVA and tagged as Tags with 2 Comments on Nested Class and its necessity with example

Example and Introduction of Nested classes in JAVA and there Types

The Java programming language allows you to define a class within another class. Such a class is called as “Nested class” and is illustrated here:

Nested Class in JAVA
Nested Class in JAVA

Nested classes are divided into two parts:  “static Nested class” and “non – static nested class”.

  1. Static Nested class : A nested class defined with keyword static is known as static Nested class.
  2. Non Static Nested Class : Non static nested class is also known as “Inner Class”. Inner Classes are further divide into two types :
    • Anonymous Class : A class which does not have any name is known as Anonymous Class.
    • Local Inner Class : A class defined within method is known as Local Inner Class.
Types of Nested Classes in JAVA
Types of Nested Classes in JAVA

Below image shows that how to define the Nested class in JAVA:

Defining Nested Class in Java
Defining Nested Class in Java

Static Nested Class :
Static nested classes do not have access to other members of the enclosing class.

Example : In JAVA API, Linked List class have declared “Entry” as static nested class.

There is no need for LinkedList.Entry to be top-level class as it is only used by LinkedList (there are some other interfaces that also have static nested classes named Entry, such as Map.Entry – same concept). And since it does not need access to LinkedList’s members, it makes sense for it to be static – it’s a much cleaner approach.

Static nested classes are accessed using the enclosing class name:

OuterClass.StaticNestedClass

For example, to create an object for the static nested class, use this syntax:

OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();

Example :

package com.G2.StaticInnerClass;
/**
 * Example of Static Inner Class
 * @author jitendra Zaa
 *
 */
public class OuterClass {

	public static void main(String[] args) {
		OuterClass.StaticNestedClass.display();
	}

	static class StaticNestedClass
	{
		static void display()
		{
			System.out.println("In Display of StaticNested Class");
		}
	}

}

Non Static Nested Class:
A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private.

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:

OuterClass.InnerClass innerObject = outerObject.new InnerClass();

Example :

package com.G2.InnerClass;

public class OuterClass {
int b = 30;
	public static void main(String[] args) {
		OuterClass.InnerClass obj = new OuterClass().new InnerClass();
		obj.display();
	}

	class InnerClass {
		public void display()
		{
			System.out.println("In Display of non static Inner Class");
		}
	}
}

Example demonstrating the simple difference in Static and non static nested class:

package com.G2.InnerClass;

public class UpperClass {
public static class StaticInnerClass {}

public class InnerClass {}

public static void main(String[] args) {
        // works
        StaticInnerClass stat = new StaticInnerClass();
        // doesn't compile
        InnerClass inner = new InnerClass();
}
}

Local Inner Class :

package com.G2.LocalInnerClass;

public class OuterClass {

	public static void main(String[] args) {
		OuterClass obj = new OuterClass();
		obj.method1();
	}

	class LocalClass {
		public void display()
		{
			System.out.println("In Display of LocalClass - Outer");
		}
	}

	public void method1()
	{
		//It Will call class outside the Method
		new LocalClass().display();

		class LocalClass {
			public void display()
			{
				System.out.println("In Display of actual LocalClass");
			}
		}
		//It Will call Inner Local Class
		new LocalClass().display();
	}
}

OutPut :
In Display of LocalClass – Outer
In Display of actual LocalClass

Anonymous Class:
A class which does not have name is known as “Anonymous class”. These classes are mostly used in AWT event handlers. It is good to use the Anonymouse class, if it is not going to be used any where else.

package com.G2.AnonymousClass;
public class ThreadSample {

	public static void main(String[] args)
	{
		Thread t = new Thread(
				new Runnable(){
					public void run()
					{
						System.out.println("In run() method");
					}
				});
		t.start();
	}
}

Why Use Nested Classes?
There are several compelling reasons for using nested classes, among them:

  • It is a way of logically grouping classes that are only used in one place.
  • It increases encapsulation.
  • Nested classes can lead to more readable and maintainable code.

Logical grouping of classes”” If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such “helper classes” makes their package more streamlined.

Increased encapsulation””Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. By hiding class B within class A, A’s members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.

More readable, maintainable code””Nesting small classes within top-level classes places the code closer to where it is used.

Related posts

2 thoughts on “Nested Class and its necessity with example”

Leave a Reply

Your email address will not be published. Required fields are marked *