• Post Reply Bookmark Topic Watch Topic
  • New Topic

A doubt with constructors  RSS feed

 
rajaraman navaneethan
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 687
Hibernate jQuery Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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 ]
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!