~/ 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/6b691496-30e0-414d-84d2-d9356b283af9/flashcard utf-8 LF