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 −
- Static nested classes
- Non-static nested classes
- Local classes
- 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