Java OCA OCP Practice Question 3211

Question

Which statement, when inserted at (1), will raise a runtime exception?

class A {}//from   w w w  .  j a v a2s.com

class B extends A {}

class C extends A {}

public class Main {
  public static void main(String[] args) {
    A x = new A();
    B y = new B();
    C z = new C();

    // (1) INSERT CODE HERE.

  }
}

Select the one correct answer.

  • (a) x = y;
  • (b) z = x;
  • (c) y = (B) x;
  • (d) z = (C) y;
  • (e) y = (A) y;


(c)

Note

Statement (a) will work just fine, and (b), (d), and (e) will cause compilation errors.

Statements (b) and (e) will cause compilation errors because they attempt to assign an incompatible type to the reference.

Statement (d) will cause compilation errors, since a cast from B to C is invalid.

Being an instance of B excludes the possibility of being an instance of C.

Statement (c) will compile, but will throw a runtime exception, since the object that is cast to B is not an instance of B.




PreviousNext

Related