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?
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.
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