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");
}
}
}- A. CCE
- B. cast ok
- C. Compilation error: cannot cast A to B
- 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
- What is printed? java List<String> strings = new ArrayList<>(); List<Integer> ints = new ArrayList<>()…
- What is printed? java Integer a = 127; Integer b = 127; Integer c = 200; Integer d = 200; System.out.println((a == b) + " " + (c == d));
- What is printed? java class Base { public void show() { System.out.print("Base "); } } class Derived extends Base { protected void show()…
- What is printed? java class Base { void greet(Object o) { System.out.print("Object "); } } class Derived extends Base { void greet(String…
- What is printed? java class Base { static void show() { System.out.print("Base.static "); } } class Derived extends Base { static void…
- What is printed? java class Base { protected int code = 1; } class Derived extends Base { int code = 2; } // in main: Base b = new…