| Author |
A doubt with constructors
|
rajaraman navaneethan
Ranch Hand
Joined: Feb 26, 2005
Posts: 85
|
|
hi friends, kindly go through the following class and explain me the working. i did not find this in any practical work,but am just curious to know how it works. class cons1 { cons1(String s) { System.out.println(s); } } class cons2 extends cons1 { cons2() { super("XYZ"); cons2 obj=new cons2(); obj.dis(); } void dis() { System.out.println("In dis"); } public static void main(String args[]) { new cons2(); System.out.println("In main"); } } when i compile and execute using my compiler i get the o/p as XYZ printing so many times.why is not the method dis() called or the System.out.println of main work? i did not use ay IDE and used only notepad. regards, Raja
|
 |
Devesh H Rao
Ranch Hand
Joined: Feb 09, 2002
Posts: 687
|
|
The line of code in bold above will lead to a recursive instantiation of cons2. You are constructing an object of cons2 in the constructor of cons2. Method dis() will never get called nor will the execution reach the SOP in main. [ November 24, 2005: Message edited by: Devesh H Rao ]
|
 |
 |
|
|
subject: A doubt with constructors
|
|
|