Java OCA OCP Practice Question 1873

Question

What is the label of the first line that will cause compilation to fail in the following program?.


// Filename: MyClass.java
class MyClass {// ww  w .  j a v a 2 s  .c om
  public static void main(String[] args) {
    MyClass a;
    MySubclass b;

    a = new MyClass();             // (1)
    b = new MySubclass();          // (2)

    a = b;                         // (3)
    b = a;                         // (4)

    a = new MySubclass();          // (5)
    b = new MyClass();             // (6)
  }
}

class MySubclass extends MyClass {}

Select the one correct answer.

  • (a) (1)
  • (b) (2)
  • (c) (3)
  • (d) (4)
  • (e) (5)
  • (f) (6)


(d)

Note

(4) will cause a compile-time error, since it attempts to assign a reference value of a supertype object to a reference of a subtype.

The type of the source reference value is MyClass and the type of the destination reference is MySubclass.

(1) and (2) will compile, since the reference is assigned a reference value of the same type.

(3) will also compile, since the reference is assigned a reference value of a subtype.




PreviousNext

Related