In the example below, it prints out "true" when the Child objects a and b are different. Should I overide equals and hashCode method for every class which extends Person?
public class EqualsTest {
public static void main(String[] args){
Child a = new Child("Tom",10,1);
Child b = new Child("Tom",10,2);
System.out.println(a.equals(b));
}
}
class Person{
private String name;
private int height;
private volatile int hashCode = 0;
public Person(String n, int h){
this.name = n;
this.height = h;
}
@Override
public boolean equals(Object obj) {
if(this == obj){
System.out.println("hello");
return true;
}
if(obj instanceof Person){
Person a = (Person)obj;
if(this.name.equals(a.name)){
return true;
}else{
return false;
}
}else{
return false;
}
}
@Override
public int hashCode () {
final int multiplier = 23;
if (hashCode == 0) {
int code = 133;
code = multiplier * code + name.hashCode();
code = multiplier * code + new Integer(height).hashCode();
hashCode = code;
}
return hashCode;
}
}
class Child extends Person{
private int age;
public Child(String n,int h, int a) {
super(n,h);
this.age = a;
}
}
Thanks