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?