Junior — Middle
How do you compare two objects considering their specific type when using the equals method?
sobes.tech AI
Answer from AI
When implementing the equals method in Java, it is important to:
- Check that the object being compared to is not
null. - Check that the objects are of the same type (usually using
instanceofor class comparison). - Compare the significant fields of the objects for equality.
Example implementation of the equals method considering the type:
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
MyClass other = (MyClass) obj;
return Objects.equals(this.field1, other.field1) && this.field2 == other.field2;
}
Here, getClass() ensures that the objects are of exactly the same class, not subclasses. If a more flexible check is needed, instanceof can be used, but then potential issues with symmetry should be considered.