I'm doing a course in Java and very frequently when equals
method is defined in new classes its argument is Object
rather than the actual type of the class. Code example:
public class TestClass {
String label, value;
public TestClass(String label, String value) {
this.label = label;
this.value = value;
}
public boolean equals(Object o) {
TestClass t = (TestClass) o;
return this.value.equalsIgnoreCase(t.value);
}
}
Why is this a good practice? Maybe if I want to use polymorphism later this would be helpful. Is it a good practice to use Object
as argument even if I don't think currently that I'll need polymorphism but I should still account for it just in case?
Also what bothers me is that we never check whether the object will actually be of type TestClass
. Why should we have an instanceof
check?