Consider the sample code given below:
Abstract Name
public abstract class Name {
private String name;
public Name(String name)
{
this.name=name;
}
public String toString()
{
return name;
}
public String getName() {
return name;
}
}
FirstName
public class FirstName extends Name {
FirstName(String name) {
super(name);
}
public String toString()
{
return getName();
}
}
LastName
public class LastName extends Name{
LastName(String name) {
super(name);
}
public String toString()
{
return getName();
}
}
TestName
public class TestName {
public static void main(String[] args) {
Set<Name> names=new HashSet<Name>();
names.add(new FirstName("George"));
names.add(new LastName("Bush"));
names.add(new FirstName("Bush"));
System.out.println(names);
}
}
Output
[Bush, Bush, George]
Now the question is how to override hashcode and equal's method such that I have only one name "Bush" either as the first name or the last name ?