Polymorphism

AP Computer Science A· difficulty 4/5

public class A {
    public String x() { return "A.x"; }
    public String y() { return x(); }
}
public class B extends A {
    public String x() { return "B.x"; }
}
public class C extends B {
    public String y() { return "C.y"; }
}
// Usage:
A obj = new C();
System.out.print(obj.y());

What is printed?

  • A

    A.x

  • B

    C.y

    check_circle
  • C

    B.x

  • D

    Compile error

Explanation

Dynamic dispatch picks the most-derived override of y, which is C's y returning "C.y".

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

Related questions