Polymorphism

AP Computer Science A· difficulty 2/5

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

What is printed?

  • A

    AB

  • B

    B

    check_circle
  • C

    Compile error

  • D

    A

Explanation

Method dispatch in Java is based on the runtime (actual) type of the object, not the declared type. obj refers to a B object, so B's name() is called, printing "B".

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

Related questions