• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Tim Cooke
  • Jeanne Boyarsky
  • Liutauras Vilda
Sheriffs:
  • Frank Carver
  • Henry Wong
  • Ron McLeod
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Piet Souris
  • Himai Minh

A doubt with constructors

 
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 687
Hibernate jQuery Spring
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 ]
 
This cake looks terrible, but it tastes great! Now take a bite out of this tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic