Overriding Methods

AP Computer Science A· difficulty 4/5

public class Animal {
    private String name;
    public Animal(String n) { name = n; }
    public boolean equals(Object o) {
        if (!(o instanceof Animal)) return false;
        return name.equals(((Animal) o).name);
    }
}
// Usage:
Animal a = new Animal("Rex");
Animal b = new Animal("Rex");
System.out.print(a.equals(b));

What is printed?

  • A

    ClassCastException

  • B

    false

  • C

    Compile error

  • D

    true

    check_circle

Explanation

Both have name "Rex". The instanceof check passes; String.equals on the names returns true.

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

Related questions