File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes From Kathy's book :Recursive constructor invocation Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "From Kathy Watch "From Kathy New topic

From Kathy's book :Recursive constructor invocation

Ambapali Pal
Ranch Hand

Joined: Dec 17, 2002
Posts: 47
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(String s){A() ;)
Case 2:
public void go(){
public void doStuff(){
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,
[ January 27, 2003: Message edited by: Thomas Paul ]
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
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.
Kathy Sierra
Cowgirl and Author

Joined: Oct 10, 2002
Posts: 1589
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 : )
Ambapali Pal
Ranch Hand

Joined: Dec 17, 2002
Posts: 47
Thank you Jose and Kathy.
Sarma Lolla
Ranch Hand

Joined: Oct 21, 2002
Posts: 203
Can any one explain what are the other situations that lead to a stack overflow?
I agree. Here's the link:
subject: From Kathy's book :Recursive constructor invocation
It's not a secret anymore!