super Keyword

AP Computer Science A· difficulty 4/5

public class A {
    public String name() { return "A"; }
    public String label() { return "[" + name() + "]"; }
}
public class B extends A {
    public String name() { return "B"; }
}
System.out.println(new B().label());

What is printed?

  • A

    [B]

    check_circle
  • B

    [A]

  • C

    []

  • D

    Compile-time error

Explanation

<code>label()</code> is inherited from A but calls <code>name()</code> on <code>this</code>. Since this is a B, dynamic dispatch picks B.name().

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

Related questions