| Author |
this operator
|
Gagan Deep
Ranch Hand
Joined: Aug 23, 2005
Posts: 47
|
|
Q43.What will be the result of compiling and running the given program? Select one correct answer. 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. } 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. Answer is 3. Can some once help me in understanding this?
|
 |
Mike Noel
Ranch Hand
Joined: Dec 15, 2005
Posts: 108
|
|
I don't understand the error either. I think that it has to do with constructor chaining and that's something that I only have a basic grasp on. I did a search in the forums and found some discussion about this here: http://www.coderanch.com/t/244427/java-programmer-SCJP/certification/When-does-become-availible The compilation error is If you search for this in the forum search you'll find another dozen or so topics that discuss it. _M_
|
Mike Noel
|
 |
A Kumar
Ranch Hand
Joined: Jul 04, 2004
Posts: 973
|
|
you cannot use instance variables for constructor chaining You can use static variables.
|
 |
santosh kothapalli
Greenhorn
Joined: Dec 27, 2005
Posts: 26
|
|
Hi, The simplest of answers is you cannot use the instance variables in construstors to expressions or calculations ,but only to initialize else the compiler throws an error. Just to make it official, you can find the rule in the JLS 8.8.5.1
|
Santosh K<br />SCJP 1.4,SCWCD
|
 |
Gagan Deep
Ranch Hand
Joined: Aug 23, 2005
Posts: 47
|
|
Thanks to all for replying. i found the following from the link suggested by santosh An explicit constructor invocation statement in a constructor body may not refer to any instance variables or instance methods declared in this class or any superclass, or use this or super in any expression; otherwise, a compile-time error occurs. Thanks Gagan.
|
 |
 |
|
|
subject: this operator
|
|
|