开发者

Override equal's and hashCode for abstract super class

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 开发者_StackOverflow社区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 ?


You probably want something like this:

 public boolean equals(Object obj)
 {
   if (obj == null)
     return false;
   if (!(obj instanceof Name))
     return false;
   Name name = (Name) obj;
   return this.name.equals(name.name);
 }

 public int hashCode()
 {
   return name.hashCode();
 }


you should provide a custom equals method, not the default one. by contract a FirstName and a LastName can never be equal, because they are 2 different classes (with the same content in this case).

edit: generated equals method from eclipse:

public boolean equals( Object obj )
{
    if ( this == obj )
        return true;
    if ( obj == null )
        return false;
    if ( getClass() != obj.getClass() )
        return false;
    Name other = (Name) obj;
    if ( name == null )
    {
        if ( other.name != null )
            return false;
    }
    else if ( !name.equals( other.name ) )
        return false;
    return true;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜