These two little braces in
SomeClass sac2 = new SomeClass() {};
cause a lot of automatic behavior in Java. Here's what happens when this line is executed:
- An anonymous subclass of
SomeClass . - This anonymous subclass defines a constructor with no arguments by default, like any other Java class declared without a constructor without arguments.
- The default constructor without arguments is determined by the visibility
public - A default constructor without arguments is defined as a call to
super() (this is what no-arg constructors always do). - The
new command calls the constructor without arguments of this anonymous subclass and assigns the result to sac2 .
A constructor with no default arguments in an anonymous subclass of SomeClass has access to the protected SomeClass , because an anonymous subclass is a descendant of SomeClass , so the call to super() is SomeClass new operator invokes this constructor without default arguments, which has public visibility.
source share