consider two classes like this
class Name{
string name;
public Name(String name){
this.name = name;
}
public boolean equals(Object obj){
if(! obj instanceof Name){
return false;
}
return name.equals(((Name)obj).name);
}
}
class NameWithInitial extends Name{
char initial;
public NameWithInitial(String name, char initial){
super(name);
this.initial = initial;
}
public boolean equals(Object obj){
if(! obj instanceof NameWithInitial){
return false;
}
else{
return super.equals(obj) && initial == ((NameWithInitial)obj).initial);
}
}
}
Now run the following code:
public static void main(String[] args)
{
Name name1 = new Name("abcd");
Name name2 = new NameWithInitial("abcd", 'a');
System.out.println(name1.equals(name2)); --1
System.out.println(name2.equals(name1)); -- 2
}
line 1 returns true while line2 returns false.
However, the contract of the object method says:
" It is symmetric: for any reference values x and y, x.equals(y)
should return true if and only if y.equals(x) returns true. "
-- how to correct this problem? what problem will I face, if i don't correct this?