Consider the following program:
public class A
{
public static void main(String[] args)
{
class B
{
private B()
{
System.out.println("local");
}
}
// how are we able to create the object of the class having private constructor
// of this class.
B b1= new B();
System.out.println("main");
}
}
Output: local main
A class having private constructor means we can create object inside the class only, but here am able to create instance outside the class. can someone explain how are we able to create the object of B outside class B??
Because a Top Level Class is a happy family, everyone can access one another despite private.
JLS 6.6.1
6.6.1. Determining Accessibility
- A member (class, interface, field, or method) of a reference (class, interface, or array) type or a constructor of a class type is accessible only if the type is accessible and the member or constructor is declared to permit access:
- Otherwise, if the member or constructor is declared
private, then access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.
Because a Top Level Class is a happy family, everyone can access one another despite private.
JLS 6.6.1
6.6.1. Determining Accessibility
- A member (class, interface, field, or method) of a reference (class, interface, or array) type or a constructor of a class type is accessible only if the type is accessible and the member or constructor is declared to permit access:
- Otherwise, if the member or constructor is declared
private, then access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor.
You're allowed to even access private variables of that class too (try it!).
This is because you are defining that class inside the same class your calling it from, so you have private/internal knowledge of that class.
If you move Class B outside of Class A, it will work as expected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With