Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is it possible to create instance outside class of local inner class having private constructor?

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??

like image 579
user1652549 Avatar asked Dec 06 '25 07:12

user1652549


3 Answers

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.
like image 159
johnchen902 Avatar answered Dec 07 '25 21:12

johnchen902


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.
like image 41
johnchen902 Avatar answered Dec 07 '25 21:12

johnchen902


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.

like image 30
Andrew Avatar answered Dec 07 '25 20:12

Andrew