| Author |
two constructors call each other..
|
Murgan Sub
Greenhorn
Joined: Feb 06, 2002
Posts: 22
|
|
What happens when two constructors call each other? Can you get an infinite loop out of the process? public class ConsRecurs { public ConsRecurs(int i) { this(i*1.0); } public ConsRecurs(double d) { this((int)d); } public static void main(String[] a) { System.out.println("About to construct..."); new ConsRecurs(Math.PI); System.out.println("Hey, I'm still alive!"); } }
|
 |
Brian Lugo
Ranch Hand
Joined: Nov 10, 2000
Posts: 165
|
|
You will get a stack overflow error! This is a good example. When you have multiple constructors and if there is a situation where each constructor calls another constructor through "this()" method call, then there needs to be atleast one constructor which does not have "this()" method call on its first line. It can have super or nothing. Brian [ February 15, 2002: Message edited by: Brian Lugo ]
|
 |
Dave Vick
Ranch Hand
Joined: May 10, 2001
Posts: 3244
|
|
Murgan From the JLS section 8.8.5:
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.
Both JBuilder and JDeveloper caught it when I tried it. Hope that answers it for you.
|
Dave
|
 |
Brian Lugo
Ranch Hand
Joined: Nov 10, 2000
Posts: 165
|
|
I don't think you get a compile time error, for this example, with existing compilers. I believe this specification has not been implemented in the existing compilers. Feel free to correct me if I am wrong. I wrote this program a while back: Compile it and run it . The IDE that I was using froze, so be careful. It might be worth executing it from command line. Brian [ February 15, 2002: Message edited by: Brian Lugo ] [ February 15, 2002: Message edited by: Brian Lugo ]
|
 |
Roy Ben Ami
Ranch Hand
Joined: Jan 13, 2002
Posts: 732
|
|
actually you are right brian. i use the jdk 1.4 and both exmamples compile but will get stuck at runtime.
|
 |
keerthidhar dongre
Greenhorn
Joined: Jan 30, 2002
Posts: 26
|
|
|
When I tried to run in Jbuilder (version 3) it said "cyclic 'this' constructor calls involving constructor TestConstChain(int) "
|
 |
Valentin Crettaz
Gold Digger
Sheriff
Joined: Aug 26, 2001
Posts: 7610
|
|
What the JLS has to say about recursive constructor invocation: 15.9.6 Example: Evaluation Order and Out-of-Memory Detection
|
SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
|
 |
Brian Lugo
Ranch Hand
Joined: Nov 10, 2000
Posts: 165
|
|
Originally posted by keerthi dongre: When I tried to run in Jbuilder (version 3) it said "cyclic 'this' constructor calls involving constructor TestConstChain(int) "
My guess is JBuilder IDE has a check in it or it is not using SUN's java compiler.
|
 |
 |
|
|
subject: two constructors call each other..
|
|
|