Overriding equals()
Part of: Inheritance
Comparing Objects The other key inherited method from Object is equals() . By default, Object.equals() compares references , meaning two objects are equal only if they are the same object in memory . Often we want value equality instead: two distinct objects are equal if their fields match. == vs equals - == compares references (are these the same object?). - .equals() compares whatever the method defines (often field values). Overriding equals() The standard pattern takes an Object parameter, checks the type, casts, and compares fields: Step by step: - instanceof confirms the argument is actually a Point (and not null). - The cast (Point) o lets you reach the other object's fields. - The comparison returns true only when all relevant fields match. Why the Object Parameter? The signature must be public boolean equals(Object o) to truly override the inherited method. If you wrote equals(Point p) instead, you would be overloading , not overriding, and collections like ArrayList.contains would not use it. Common Pitfalls - Forgetting instanceof causes a ClassCastException when comparing to other types. - Using == on String fields compares references; use .equals() for strings. In the
Challenge: Point Equality