Polymorphism

AP Computer Science A· difficulty 3/5

public class A {
    public String show() { return "A"; }
}
public class B extends A {
    public String show() { return "B"; }
}
public static String pick(A x) { return x.show(); }
System.out.println(pick(new B()));

What is printed?

  • A

    AB

  • B

    Compile-time error

  • C

    B

    check_circle
  • D

    A

Explanation

Even though the parameter is declared as A, the actual object is B; dynamic dispatch calls B.show().

Want 10 more like this — adaptive to your weak spots?

Related questions