~/ learn/ java-from-zero/ cards/ equals, hashCode & toString done right
1 of 4

Type a correct equals method using pattern matching instanceof

Type a correct equals method using pattern matching instanceof

Answer

@Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Point p)) return false; return x == p.x && y == p.y; }

The identity check short-circuits the common case. !(o instanceof Point p) handles null (instanceof returns false for null) and wrong types in one step. Accessing p.x inside a non-public class is valid — private visibility is class-wide.

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/e17f6566-5fd0-4dc0-a6b0-8b23459362fb/flashcard utf-8 LF