Unit 3 Cycle 2 Day 12: equals() Override Correctness
Share
equals() Override Correctness
Section 3.16 — Object Superclass
Key Concept
A correct equals() override must accept an Object parameter (not the specific class type) to properly override the inherited version. Inside, it should check if the parameter is the same type using instanceof, then cast it and compare fields. A method like boolean equals(Dog other) does not override Object.equals() — it overloads it. The AP exam tests whether an equals method correctly overrides the superclass version versus accidentally creating an overload that is never called polymorphically.
Consider the following class.
What does the following return?Card c1 = new Card("Hearts", 10); Card c2 = new Card("Hearts", 10); System.out.println(c1.equals(c2));
Answer: (A) true
c1.equals(c2): casts c2 to Card. suit: "Hearts".equals("Hearts")=true. rank: 10==10=true. Both true: returns true.
Why Not the Others?
(B) Both cards have identical suit and rank, so equals returns true.
(C) The cast succeeds because c2 is actually a Card object.
(D) The equals method correctly overrides Object's equals(Object).
Common Mistake
The equals override must take Object as the parameter type (not Card) to properly override Object.equals(). The cast inside is needed to access Card-specific fields.
AP Exam Tip
A proper equals() override: parameter type must be Object, cast to the correct type, then compare fields. Using Card as the parameter type would be overloading, not overriding.