java中==与equals的区别

基本数据类型使用==比较的是数据
*
引用数据类型==比较的地址
*
引用数据类的内容的比较要使用equals
*
因为object的equals比较的还是引用,无法满足子类的要求,需要子类重写

 在Animal类中将eaquls进行重写

 public boolean equals(Object obj) {
        //如果obj是null,直接返回false
        if (obj == null) {
            return false;
        }
        //如果两个引用变量指向同一个对象,直接返回true
        if (this == obj) {
            return true;
        }
        Animal other = (Animal) obj;
        //如果color和age都相等,返回ture
        if (this.color == other.color && this.age == other.age) {
            return true;
        }else {
            return false;
        }
    }

 在Dog类中将equals进行重写

 public boolean equals(Object obj) {
        boolean flag = super.equals(obj);
        if (flag) {
            //在比较nickName和type
            Dog other = (Dog) obj;
           // if (this.nickName == other.nickName && this.type == other.type) {
            if (this.nickName.equals(other.nickName) && this.type.equals(other.type)) {

                return true;

            } else {
                return false;
            }
        }else
        {
            return false;
        }
    }

 这里 if (this.nickName.equals(other.nickName) && this.type.equals(other.type))

 中的“equals”,点击ctrl+左击查看其代码段

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值