首页 > 其他分享 >Object

Object

时间:2022-10-10 19:00:08浏览次数:32  
标签:return name Object Dog equals toString

Object

构造方法

Object()

常用操作

可以被子类覆盖的方法

equals

toString

hashCode

finalize

protected方法,使用前需要覆盖

clone

多线程相关不能被覆盖

wait

notify

notifyAll

不能被覆盖

getClass

1.equals

方法的重写,当时new了dog对象

对比两个属性相同对象的时候,发现输出为flase,因为equals方法是继承的Object基类,所以为了达到我们想象的输出结果,这个方法并不合适,就需要我们重写方法。

在Dog类里,默认继承Object类,所以我们需要重写equals方法

 @Override
	//重写开始是地址值对比的equals的方法,现在开始自定义时间
    public boolean equals(Object obj) {
        //obj属于Dog的实体,就强制转换
        if(obj instanceof  Dog){
            Dog dog1 = (Dog) obj;
            if(dog1.getAge()!=this.getAge()){
                return false;
            }
            //比较第二个条件
            if(!dog1.getColor().equals(this.getColor())){
                return  false;
            }
            //比较第二个条件
            if(!dog1.getName().equals(this.getName())){
                return  false;
            }
            return true;

        }
        return false;
    }
}

2.toString()

我们发现开始toString()打印的时候,输出的是地址值。

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

note.Ojb.Dog@27ddd392
true
note.Ojb.Dog@27ddd392

和我们想象的结果不一样。

那么如上操作

@Override
public String toString() {
    return "Dog{" +
            "name='" + name + '\'' +
            ", age=" + age +
            ", color='" + color + '\'' +
            '}';
}

Dog{name='小黑', age=4, color='black'}
true
Dog{name='小黑', age=4, color='black'}

标签:return,name,Object,Dog,equals,toString
From: https://www.cnblogs.com/seeingxi/p/16776820.html

相关文章