What is the result?


And given the code fragment:

What is the result?
A. Compilation fails at line n2.
B. Compilation fails at line n1.
C. 20:20
D. 10:20

Download Printable PDF. VALID exam to help you PASS.

11 thoughts on “What is the result?

  1. This ones checks if you know the flow of constructors. Remember that super() would have been called implicitly if a super(y) wasn’t called so thats something to look out for. Also, the super(x) had to be the first line of the constructor otherwise compilation would have failed. I got 20:20

  2. Answer C, 20:20
    The call of “new Car(20)” will invoke the Car(int y) constructor, which in turn invoke the Vehicle(int x) constructor via the super(y) call out. This leads to setting the value of x at Vehicle to 20 by the Vehicle(int x) constructor. When that is done, compiler comes back to the Car(int y) constructor and executes the “this.y = y” line, which leads to setting up the int y of the Car to 20. Finally, when the println(y) method is executed, and is requested to print something that is neither a String nor a primitive value, (in our case it is requested to print the object reference “y”), therefore, it will invoke the toString() method of Object (i.e. the grant parent class of all objects). But because the Car class has a toString() method that is overriding the original toString() method of the Object class, it will then return the line (super.x + “:” + this.y), which at the end prints 20:20.

Leave a Reply

Your email address will not be published. Required fields are marked *

The reCAPTCHA verification period has expired. Please reload the page.