Which of the following statements are true? a. A constructor can invoke another constructor of the same class using the constructor invocation statement "this". b. A constructor can invoke itself using the constructor invocation statement "this". c. The constructor invocation statement, "this", can legally appear anywhere in the constructor body. d. A constructor can invoke the constructor of the direct superclass using the superclass constructor invocation statement "super". e. The number of constructor invocation statements that may appear in any constructor body can equal but not exceed the number of alternate constructors declared in the same class. f. A constructor is not permitted to throw an exception. g. None of the above.
The correct answers are A and D But my doubt is related to option B that is given. The answer given to justify B is : "A compile-time error is generated if a constructor attempts to invoke itself either directly or indirectly" I had also marked it true, but later found out that the compiler cries out foul if I have code like this.
But if I comment this() statement at line marked 1, and uncoment the next line, i.e new A(), the thing does not create a compiler error, though and infinite loop is create and the system soon runs out of stack. Can anybody please provide a justification for this behaviour. Why is new A() allowed and not this() ?? Rgds, Anupreet
Hi, The main purpose of a constructor is to initialize the state of the object. It makes sence to not allow recursion to this type of work as one want to initialze the state only once at the beginning. So j2sdk1.4 compiler reports this as On the other hand will create a new Object by calling the same constructor it is in. And it goes on creating the objects and filling up the stack. -A
Let's say you wrote a class something like the following:
When executed, main() will create a new ThisTest by calling the no-arg constructor, which calls the int-arg constructor, which tries to call the no-arg constructor. That is a way of indirectly trying to make a recursive constructor call. The compiler detects the attempted recursion and (rightly) complains:
Hope this helps! Regards, Jeff
Give a man a fish, he'll eat for one day. Teach a man to fish, he'll drink all your beer.
Cheers, Jeff (SCJP 1.4 all those years ago...)
I wonder if this output is dependent upon the JVM that we use. Ur example is the same as the one I cited, except for the class names, and I donot get any compile time exception. At run time I get things like StackOverflow! :roll:
Today's lesson is that you can't wear a jetpack AND a cape. I should have read this tiny ad:
a bit of art, as a gift, that will fit in a stocking