Link_pg
Novembro 8, 2007, 3:26am
#1
Olá!
Thought question: What do you think will happen if you try to compile the
following code?
class A {
A() {
this("foo");
}
A(String s) {
this();
}
}
Your compiler may not actually catch the problem (it varies depending on your compiler, but most won’t catch the problem). It assumes you know what you’re doing. Can you spot the flaw? Given that a super constructor must always be called, where would the call to super() go? Remember, the compiler won’t put in a default constructor if you’ve already got one or more constructors in your class. And when the compiler doesn’t put in a default constructor, it still inserts a call to super() in any constructor that doesn’t explicitly have a call to the super constructor—unless, that is, the constructor already has a call to this(). So in the preceding code, where
can super() go? The only two constructors in the class both have calls to this(), and in fact you’ll get exactly what you’d get if you typed the following method code:
public void go() {
doStuff();
}
public void doStuff() {
go();
}
Now can you see the problem? Of course you can. The stack explodes! It gets higher and higher and higher until it just bursts open and method code goes spilling out, oozing out of the JVM right onto the floor. Two overloaded constructors both calling this() are two constructors calling each other. Over and over and over,
resulting in
% java A Exception in thread “main” java.lang.StackOverflowError
Bom… eu testei aqui os códigos e no caso dos métodos realmente da um StackOverflowError… mas no caso dos construtores dai foi diferente… recebi algo como Recursive constructor invocation …
E agora? No K&B diz que da sempre StackOverflowError, mas no meu compilador da (no caso de construtores) esse Recursive constructor invocation… se houver uma pergunta desse tipo o que respondo?
Abraços
Como descrito no livro, pode dar erro de compilação ou nao.
Isso depende do compilador… o seu, por exemplo, ja detectou o erro e nao compilou, mas pode haver compiladores que nao detectem isso.
Mas uma vez o codigo compilado, em tempo de execução, sempre será lançado java.lang.StackOverflowError.
Acredito que se cair uma questão dessa na prova, as opções seriam algo como:
A) Never compiles
B) Maybe it does not compile
C) If compiles, throws java.lang.StackOverflowError at runtime
D) abobrinha 1
E) abobrinha 2
Nesse caso, as respostas seriam B e C.
[]'s