This week's book giveaway is in the Design forum.
We're giving away four copies of Building Microservices and have Sam Newman on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Constructors r behaving Strangley Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Building Microservices this week in the Design forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Constructors r behaving Strangley" Watch "Constructors r behaving Strangley" New topic
Author

Constructors r behaving Strangley

Hussain
Ranch Hand

Joined: Nov 22, 2001
Posts: 110
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

Muhammad Hussain<br />Sun Certified Java Programer (SCJP2)<br />Sun Certified Web Component Devloper SCWCD
Maulin Vasavada
Ranch Hand

Joined: Nov 04, 2001
Posts: 1873
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
 
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
 
subject: Constructors r behaving Strangley
 
jQuery in Action, 3rd edition