• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Calling constructor

 
Vishnu Munnangi
Ranch Hand
Posts: 114
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1258
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic