Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why wouldn't this recursive constructor cause compile time error?

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

like image 792
Sarabjeet Avatar asked Feb 19 '26 02:02

Sarabjeet


2 Answers

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.

like image 94
Eran Avatar answered Feb 21 '26 14:02

Eran


Your code would never pass compilation. It should give you compile time error- "recursive constructor invocation"

like image 20
rokonoid Avatar answered Feb 21 '26 16:02

rokonoid