Consider following code
class ConstructorDemo2{
ConstructorDemo2(){
this(1);
}
ConstructorDemo2(int i){
this();
}
public static void main(String[] args){
new ConstructorDemo2();
}
}
Kathy Sierra's SCJP6 book says on page 144 that
a code like this might go undetected and cause StackOverflowError. But at the same time, we know subclass constructor ALWAYS has to call the superclass constructor using super() [default provided by compiler]
but in the following code sample, both constructors are invoking this() (calling each other) .
It does show the error error: recursive constructor invocation in my OpenJDK compiler, but Kathy Sierra's book says such a code might go undetected by compiler and will throw a exception at runtime.
So if such a code sample is shown to me in SCJP/OCJP exam and asked whether it will compile, what what would be the answer ? seems a bit ambiguous
When in doubt, read what the JLS has to say :
8.8.7. Constructor Body
...
It is a compile-time error for a constructor to directly or indirectly invoke itself through a series of one or more explicit constructor invocations involving this.
Therefore, your code shouldn't pass compilation. If some compiler doesn't detect this error, it doesn't comply with the Java language specification.
Your code would never pass compilation. It should give you compile time error- "recursive constructor invocation"
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