java——覆写equals

2019年2月16日21:45:48 发表评论 1,248 views
/**
 * Created by xabcd on 2019/2/16.
 */
public class person_equals
{
    private String name;
    private int age;
    public person_equals(String name,int age)
    {
        this.name = name;
        this.age = age;
    }
    //覆写父类(Object类)红的equals方法
    public boolean equals(Object o)
    {
          boolean  temp =true;
    //声明一个对象,此对象实际上就是当前调用的equals方法的对象
    person_equals p1 = this;
    //判断Object类对象是否是Person的实例
    if(o instanceof person_equals)
    {
        //如果是Person类实例,则进行向下转型
        person_equals p2 = (person_equals)o;
        //调用String类中的equals方法
        if(!(p1.name.equals(p2.name)&&p1.age==p2.age))
        {
            temp = false;
        }
    }
    else
    {
        //如果不是pereson_equals类实例,则直接返回false
        temp = false;
    }
    return temp;
}
}




/**
 * Created by xabcd on 2019/2/16.
 */
public class test_equals1
{
    public static void main(String[] args) {
        person_equals p1 = new person_equals("张三", 25);
        person_equals p2 = new person_equals("张三", 25);
        System.out.println(p1.equals(p2) ? "是同一个人" : "不是同一个人");
    }

}



结果:
是同一个人

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: