~/ learn/ java-from-zero/ cards/ Practical Java for the Job
1 of 24

Type a correct equals override using instanceof pattern matching

Type a correct equals override using instanceof pattern matching

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. instanceof with a pattern variable safely handles null (instanceof null is always false) and binds p for field access in one step. No NPE risk.

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/8fa37489-d406-4464-b339-c068afe9014a/flashcard utf-8 LF