File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Calling constructor Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Calling constructor" Watch "Calling constructor" New topic

Calling constructor

Vishnu Munnangi
Ranch Hand

Joined: Sep 28, 2004
Posts: 114
Hi Everyone,
This is a Question from one of the Mock exams. Please go through the code...
1. class Q43
2. {
3. int y=1;
4. Q43()
5. {
6. this(y);
7. }
8. Q43(int x)
9. {
10. y=x++ + ++x;
11. }
12. public static void main(String [] args)
13. {
14. Q43 t = new Q43();
15. System.out.println(t.y);
16. }
17. }
What is the attempt to compile and run the program?
1. Program compiles correctly and prints 1 when executed.
2. Program compiles correctly and prints 4 when executed.
3.Compile time error.
4.None of above.

The answer given is 3. Compile time error.

I am of the opinion that answer 2 is correct, because when the object t is created it calls the no argument constructor, which inturn calls the single argument constructor. from there the value of y will be assigned value of 4 which will be printed.
but when i compiled it, it is giving me the error saying that " cannot reference y before supertype constructor has been called "
Can any one explain me what is happening.

Thanks in Advance.
Peixiao Lin

Joined: Oct 04, 2004
Posts: 28
In this case, y is an instance variable. It only can be accessed when it's associated with an instance created by constructor. So every time when you try to instantiate this class, when constructor is invoked, compiler don't know where is y value. That is where the error is.
Nathaniel Stoddard
Ranch Hand

Joined: May 29, 2003
Posts: 1258
Basically, instance variables aren't considered "alive" until the superconstructors completes. Superconstructors can't complete until the super() gets called, either by by default or explicitly. In your case, you're attempting to reference y before that happens, which would have happened by default as the first operation in Q43(int). Ergo the operation.

I agree. Here's the link:
subject: Calling constructor
jQuery in Action, 3rd edition