Java 11

Java 11 – Nested Based Access

Java 11 introduced a concept of nested class where we can declare a class within a class. This nesting of classes allows to logically group the classes to be used in one place, making them more readable and maintainable. Nested class can be of four types −

  1. Static nested classes
  2. Non-static nested classes
  3. Local classes
  4. Anonymous classes

Java 11 also provide the concept of nestmate to allow communication and verification of nested classes.

Consider the following program −

import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;

public class Java11NestedClass {
	
   public static void main(String[] args) {	
	  // 1. Get nested class names
      Set<String> nestedMembers = Arrays.stream(Java11NestedClass.class.getNestMembers())
						         .map(Class::getName)
						         .collect(Collectors.toSet());
      System.out.println(nestedMembers);
	      
      // 2. Check is nest mate class
      boolean isNestMate = Java11NestedClass.class.isNestmateOf(Inner.class);
      System.out.println(isNestMate);
      isNestMate = Java11NestedClass.class.isNestmateOf(Inner3.class); // Inner3 class not nested class
      System.out.println(isNestMate);
     
      // 3. Get nest host class
      boolean nestHost = Inner.class.getNestHost() == Java11NestedClass.class;
      System.out.println(nestHost);
      nestHost = Inner3.class.getNestHost() == Java11NestedClass.class;  // Inner3 class not nested class of Java11NestedClass
      System.out.println(nestHost);
	}

	public class Inner{}
	
	public class Inner1{}

}

 class Inner3{}

Output

[Java11NestedClass$Inner, Java11NestedClass, Java11NestedClass$Inner1]
true
false
true
false

About the Author: Elavarasan PK

Technical Specialist, Intersoft Data Labs