ProgrammingHardAccenture · Cognizant pattern

What is printed?

What is printed?
class Animal {
    String name;
    Animal(String n) { name = n; }
    @Override
    public boolean equals(Object o) {
        if (!(o instanceof Animal)) return false;
        return name.equals(((Animal) o).name);
    }
    @Override
    public int hashCode() { return name.hashCode(); }
}
class Dog extends Animal {
    Dog(String n) { super(n); }
}
public class Main {
    public static void main(String[] args) {
        Animal a = new Animal("Rex");
        Dog d = new Dog("Rex");
        System.out.print(a.equals(d) + " " + d.equals(a));
    }
}
  1. A. false false
  2. B. true true
  3. C. true false
  4. D. false true

Correct answer: B. true true

Animal.equals checks `o instanceof Animal` (not getClass() comparison), and Dog is-an Animal, so a.equals(d) compares names and returns true. d.equals(a) uses the same inherited equals(), also true — symmetric in this case because the check is instanceof-based rather than exact-class-based.

More OOP with C++ and Java questions

Exams that ask this topic