Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the access modifier of an anonymous class's constructor?

NOTE: This is a self-answered question. It may be a very simple one but I thought it would be worth sharing.

Suppose I have an anonymous class declaration:

MyObject myObj1 = new MyObject() {

};

where MyObject is:

class MyObject {

    public MyObject() { // explicit public constructor
    }

    ...
}

From this section of the Java Language Specification (emphasis mine):

An anonymous class cannot have an explicitly declared constructor. Instead, an anonymous constructor is implicitly declared for an anonymous class.

If I try to get the number of public constructors:

// Number of public constructors; prints 0
System.out.println(myObj1.getClass().getConstructors().length);

it prints zero as expected, i.e. the anonymous constructor is not public.

It is also not private, since if we call the following from a different class in the same package where the anonymous class is defined (by passing around the instance myObj1):

myObj1.getClass().getDeclaredConstructor().newInstance();

it completes without an IllegalAccessException.

What is the access modifier of the implicit constructor in an anonymous class?

like image 758
M A Avatar asked Nov 20 '15 21:11

M A


1 Answers

The anonymous constructor acts similar to the default constructor that the compiler also creates for a normal class that does not declare constructors. In this case:

In a class type, if the class is declared public, then the default constructor is implicitly given the access modifier public (§6.6); if the class is declared protected, then the default constructor is implicitly given the access modifier protected (§6.6); if the class is declared private, then the default constructor is implicitly given the access modifier private (§6.6); otherwise, the default constructor has the default access implied by no access modifier.

In other words, the anonymous constructor is only accessible in the same package as the anonymous class.

like image 82
M A Avatar answered Sep 28 '22 05:09

M A