Forums Register Login

From Kathy's book :Recursive constructor invocation

+Pie Number of slices to send: Send
There is some ambiguity coming here when testing in j2sdk1.4.1_01 .
This is from chapter 5 in Kathy and Bert's book. Below is the code given.
Case 1:
class A{
A(){this("foo");}
A(String s){A() ;)
}
Case 2:
public void go(){
doStuff();
}
public void doStuff(){
go();
}
The book says that it depends upon compiler. The compiler may not catch this problem and running them will give a stack overflow in both the cases.
When I try them seperately in j2sdjk1.4.1_01
case 1 gives me compiler error for recursive constructor invocation.
But case 2 compiles fine and gives stack overflow as indicated in the book.
It looks to me that the same compiler behaving differently for constructor and normal method . Which is surprising ! I could not find anything about this in the JLS also. Hope this kind of question will not be there in the exam.
May be somebody can throw some light on it.
Thank you,
Ambapali
[ January 27, 2003: Message edited by: Thomas Paul ]
+Pie Number of slices to send: Send
Hi,
I think a compiler can't detect 'endless recursivity' in general. However, when dealing with constructors, it doesn't try to detect endless recursivity but cycles in chaining constructor calls. The compiler ensures that any constructor in the chain is going to call super().
Jose Francisco.
+Pie Number of slices to send: Send
Yep -- what Jose said ; )
For stack overflow, as long as you can recognize situations where it would occur, you're in good shape for the exam. You aren't expected to know if a particular compiler will stop you from, say, the constructor chaining that leads to endless recursion, but you ARE expected to recognize that if it DID compile, the stack would eventually explode.
For the exam, just be certain that you're solid on how constructors are invoked, in every scenario (with or without overloaded constructors, with or without explicit constructors, with or without explicit super() calls, etc.) and you'll be fine : )
cheers,
Kathy
+Pie Number of slices to send: Send
Thank you Jose and Kathy.
+Pie Number of slices to send: Send
Can any one explain what are the other situations that lead to a stack overflow?
It's just a flesh wound! Or a tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 766 times.
Similar Threads
Recursive constructor invocation
K&B Book Constructor issue
recursive constructor invocation
Super class constructor
Recursion
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 17:09:21.