• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Constructors r behaving Strangley

 
Ranch Hand
Posts: 110
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
hi all,
folllowing program is not compiling whyy??? help me!
class Q43 extends Object
{
int y=1;
Q43()
{
this(y);
}
Q43(int x)
{
y=x++ + ++x;
}
public static void main(String [] args)
{
Q43 t = new Q43();
System.out.println(t.y);
}
}
------------------
Muhammad Hussain
 
Ranch Hand
Posts: 1873
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Muhammad,
The code is not working because,
when you call this(y) from the no-arg const. at that time variable 'y' is not yet initialized according to the initialization mechanism. here first the constructors are started for execution and at the first step of that all the instance vars you declared are initialized but here we are calling another constructor and so it gets higher priority and gets called w/o 'y' is being yet initialized to value 1.
so it is similar situation like using a variable w/o initializing it which java doesn't allow. if we want to make sure that this is the reason then make 'y' var as static. then it works because static has higher priority in initialization and so 'y' gets initiazlied before we try to use it in the constructor!!

regards
maulin
reply
    Bookmark Topic Watch Topic
  • New Topic