问题
Let's assume we have a class:
public class SomeClass {
protected SomeClass () {
}
}
In MainClass
located in different package I tried to execute two lines:
public static void main(String[] args) {
SomeClass sac1 = new SomeClass();
SomeClass sac2 = new SomeClass() {};
}
Because of protected
constructor, in both cases I was expecting program to fail. To my suprise, anonymous initialization worked fine. Could somebody explain me why second method of initialization is ok?
回答1:
Your anonymous class
SomeClass sac2 = new SomeClass() {};
basically becomes
public class Anonymous extends SomeClass {
Anonymous () {
super();
}
}
The constructor has no access modifier, so you can invoke it without problem from within the same package. You can also invoke super()
because the protected
parent constructor is accessible from a subclass constructor.
回答2:
The first line fails, because SomeClass
's constructor is protected
and MainClass
is not in SomeClass
's package, and it isn't subclassing MainClass
.
The second line succeeds because it is creating an anonymous subclass of SomeClass
. This anonymous inner class subclasses SomeClass
, so it has access to SomeClass
's protected
constructor. The default constructor for this anonymous inner class implicitly calls this superclass constructor.
回答3:
Those two little braces in
SomeClass sac2 = new SomeClass() {};
invoke a lot of automatic behavior in Java. Here's what happens when that line is executed:
- An anonymous subclass of
SomeClass
is created. - That anonymous subclass is given a default no-argument constructor, just like any other Java class that is declared without a no-argument constructor.
- The default no-argument constructor is defined with visibility
public
- The default no-argument constructor is defined to call
super()
(which is what no-arg constructors always do first). - The
new
command calls the no-argument constructor of this anonymous subclass and assigns the result tosac2
.
The default no-argument constructor in the anonymous subclass of SomeClass
has access to the protected
constructor of SomeClass
because the anonymous subclass is a descendant of SomeClass
, so the call to super()
is valid. The new
statement calls this default no-argument constructor, which has public
visibility.
回答4:
Your line
SomeClass sac2 = new SomeClass() {};
creates an instance of a new class which extends SomeClass
. Since SomeClass
defines a protected constructor without arguments, a child class may call this implicitly in its own constructor which is happening in this line.
来源:https://stackoverflow.com/questions/28073047/anonymous-initialization-of-class-with-protected-constructor