logo

Nested Based Access


Show

Nested class Concept is introduced in Java 11 where we can announce a class within a class. This nesting of classes permits to logically group the class that can be used in one place, making it more readable, understandable, and maintainable. There are four types of nested classes which are given below:

  • Static nested classes
  • Non-static nested classes
  • Local classes
  • Anonymous classes

The Concept of nestmate is provided in Java 11 to permit communication and verification of nested classes.

Examine the below given example:

ApiTester.java

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

public class APITester {
   public static void main(String[] args) {
      boolean isNestMate = APITester.class.isNestmateOf(APITester.Inner.class);
      boolean nestHost = APITester.Inner.class.getNestHost() == APITester.class;

      System.out.println(isNestMate);
      System.out.println(nestHost);

      Set<String> nestedMembers = Arrays.stream(APITester.Inner.class.getNestMembers())
         .map(Class::getName)
         .collect(Collectors.toSet());
      System.out.println(nestedMembers);
   }
   public class Inner{}
}

Output

true
true
[APITester$Inner, APITester]