I am looking for guidance with regard to overriding both hashcode and equals in a subclass.
I have found a similar question here: Overriding equals() & hashCode() in sub classes ... considering super fields
But what I want is something slightly different.
Imagine this (somewhat stupid) example:
class Food {
String name;
@Override
public boolean equals(Object obj) {
if (obj instanceof Food) {
Food other = (Food)obj;
return name.equals(other.name);
}
return false;
}
@Override
public int hashCode() {
return name.hashCode();
}
}
class Vegetable extends Food {
// No additional fields here
// Some methods here
}
class Fruit extends Food {
// No additional fields here
// Some methods here
}
Given that:
- The subclasses do not add any extra fields
- in this example at least, they are basically just marker classes
- A
Fruit
andVegetable
with the same name, should not be equal
Questions:
- Would you expect the subclass equals to simply contain an
instanceof
check for the subclass and a call tosuper.equals
? - How should the hashcode be structured in an attempt to have
Fruit
andVegetable
instances with the same name have different hashcodes?