File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
Author

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(){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 ]
Anonymous
Ranch Hand

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

Joined: Oct 10, 2002
Posts: 1572
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
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?
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: From Kathy's book :Recursive constructor invocation