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?
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 modifierpublic
(§6.6); if the class is declaredprotected
, then the default constructor is implicitly given the access modifierprotected
(§6.6); if the class is declaredprivate
, then the default constructor is implicitly given the access modifierprivate
(§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.
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