What is the result?

Given:

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

Download Printable PDF. VALID exam to help you PASS.

2 thoughts on “What is the result?

  1. No issue with line N1. Because, this(10); will call the second constructor of the same class
    No issue with Line N2 as well. Because, as we know this keyword should be the first statement in the constractor but if we use super() before this() than that’s fine.

    So it will print the 100 as we printed only y in the print statement int he main.

  2. class Vehicle{
    int x;
    Vehicle(){
    this(10);
    }
    Vehicle(int x){
    this.x=x;
    }

    }
    class Car extends Vehicle{
    int y;

    Car(){
    super();//x = 10, y =0 (in the qeustion cannot super() and this in the same time because both have to in the first line )
    // this(20);//x = 10, y =20
    }
    Car(int y){
    this.y=y;
    }
    public String toString(){
    return super.x +””+this.y;
    }

    public static void main(String[] args) {
    Vehicle y = new Car();
    System.out.println(y);
    }
    }

  3. Answer D:

    The reason is because the this() is used in the second line instead of the first. However, super() should also be in the first line! Therefore, the compilation fails because we cannot add both of them explicitly in the same constructor. (i.e. you either add super() or this() ). The main reason is because the compiler will add the super() for us implicitly. So if you add super(), it will be a kind of duplicate.

Leave a Reply

Your email address will not be published.