ProgrammingHardWipro · Cognizant pattern

What is printed?

What is printed?
class A { }
class B extends A { }
class Test {
    public static void main(String[] args) {
        A a = new B();
        try {
            B b = (B) a;
            System.out.println("cast ok");
            A x = new A();
            B y = (B) x;
            System.out.println("never printed");
        } catch (ClassCastException e) {
            System.out.println("CCE");
        }
    }
}
  1. A. CCE
  2. B. cast ok
  3. C. Compilation error: cannot cast A to B
  4. D. cast ok CCE

Correct answer: D. cast ok CCE

Casting a down to B succeeds because a's actual runtime object IS a B. But casting x (a genuine A instance, not a B) to B fails at runtime with a ClassCastException, since you cannot downcast to a type the object doesn't actually belong to. The catch prints CCE after "cast ok" already printed.

More OOP with C++ and Java questions

Exams that ask this topic