Multiple choice technology programming languages

What is the output for the below code ? public class C { } public class D extends C{ } public class A { public C getOBJ(){ System.out.println("class A - return C"); return new C(); } } public class B extends A{ public D getOBJ(){ System.out.println("class B - return D"); return new D(); } } public class Test { public static void main(String... args) { A a = new B(); a.getOBJ(); } }

  1. Compile with error - Not allowed to override the return type of a method with a subtype of the original type.

  2. class A - return C

  3. class B - return D

  4. Runtime Exception

Reveal answer Fill a bubble to check yourself
C Correct answer
Explanation

Java allows covariant return types (Java 5+): an overriding method can return a subtype of the original return type. B's getOBJ() returning D (subclass of C) is valid. The reference 'a' points to a B object, so B's getOBJ() executes via dynamic dispatch, printing 'class B - return D'.

AI explanation

At compile time, a.getOBJ() is checked against A's declared return type C, but at runtime Java uses dynamic dispatch: since a actually references a B object, B's overridden getOBJ() runs. Covariant return types (introduced in Java 5) allow an override to return a subtype (D) of the original method's return type (C), so this overrides validly and prints "class B - return D".