0

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?

Yos
  • 1,276
  • 1
  • 20
  • 40

1 Answers1

1

You should do the type check yourself, just casting is not safe as you said, as it can be the wrong type, and then it will throw an ClassCastException.

The reason for using object is that you may have different classes which could be equal (although this is rare), if you don't override the object form of equals then you will face issues when you use collections, as things won't be equal that should be, as the collections will use the object form.

Theoretically there could be a generic equals interface, but the equals method predates genetics, and also being able to check any object with any other simplifies a lot of code.

jrtapsell
  • 6,719
  • 1
  • 26
  • 49