Why am I being able to access "private" nested class outside the enclosing class (first) ?
import java.util.*;
import java.lang.*;
import java.io.*;
public class hi {
static class first {
private static class nested {
void main() {
System.out.println("HELLO WORLD");
}
}
}
public static void main(String[] args) {
first.nested a = new first.nested();
a.main();
}
}
>Solution :
From JLS 6.6.1:
Otherwise, the member or constructor is declared private. Access is permitted only when the access occurs from within the body of the top level class or interface that encloses the declaration of the member or constructor.
The hi class encloses the nested class, therefore access to nested is permitted anywhere within the body of hi.