0

Can someone explain the equal method?

@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Animal other = (Animal) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } }

28th Oct 2017, 10:29 AM
oyl
3 Answers
+ 11
added comment to each step @Override public boolean equals(Object obj) { // 1 check for if it the same reference if (this == obj) return true; // 2 the sent object is null value (uninitialized) if (obj == null) return false; // 3 the objects are of different classes if (getClass() != obj.getClass()) return false; // 4 cast the compared object to Animal class Animal other = (Animal) obj; // 5 compare an inner class field called "name" if (name == null) { // 6 the "this" object name is null and the compared object is not if (other.name != null) return false; // 7 the inner class field "name" is different than the compared object } else if (!name.equals(other.name)) return false; // 8 checked all the falsey cases, meaning the objects are equal (names are equal for this specific object type) return true; } }
28th Oct 2017, 10:54 AM
Burey
Burey - avatar
+ 5
equals checks if the two obhects have exactly the same datatype and value
28th Oct 2017, 10:38 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 1
I mean the steps in the method? I dont quite understand
28th Oct 2017, 10:40 AM
oyl