Reputation: 1526
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?
Upvotes: 7
Views: 3121
Reputation: 6300
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:
SomeClass
is created.public
super()
(which is what no-arg constructors always do first).new
command calls the no-argument constructor of this anonymous subclass and assigns the result to sac2
.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.
Upvotes: 4
Reputation: 280168
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.
Upvotes: 11
Reputation: 3201
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.
Upvotes: 0
Reputation: 178333
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.
Upvotes: 3