java override equals(重写equals)

本文介绍了Java中equals方法的两种实现方式:一种是简单的属性比较,只适用于特定情况;另一种是完整的实现,包括了非空检查、类型检查及所有关键属性的比较,确保了方法的鲁棒性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

代码中包含两种重写equals的方法,一种是我自己犯懒写的简版,没有任何鲁棒性可言。看起来也随意。

另一种是很学院派的做法。从java 官方jdk文档复制原版的equals函数声明,然后重新写。

class Obj{

//类名为Obj

    double a = 1.1, b = 2.2, c = 5.0;
    
    void setValue(double a,double b, double c){
        this.a = a;
        this.b = b;
        this.c = c;
    }
    
    double getValue(){
        return a + b + c;
    }
    //equals的简写。借用“父类引用指向引入对象”
    public boolean equals(Obj o){
        if (o.a == this.a){
        return true;
        }else
            return false;
    }
}
class Cube{
    double width, depth, height;
    Cube(double width, double depth, double height){
        this.depth = depth;
        this.width = width;
        this.height = height;
    }
    //比较正统的写法:

    //1. 判断对象非空;

    //2. 校验对象是否是目标实例;

    //3.为保证程序鲁棒性,强行做类型转换;

    //4.对象中的每个参数做条件说明

public boolean equals(Object obj){
        if (obj == null)
            return false;
        if (obj instanceof Cube){
            Cube cuboid = (Cube)obj;
            if(cuboid.depth == this.depth && cuboid.height == this.height && cuboid.width == this.width){
                return true;
            }
            else return false;
        }
        else return false;
    }
}
public class TestObject {

    public static void main(String[] args) {
        Obj ta = new Obj();
        //ta.setValue(5);
        Obj tb = new Obj();
        //tb.setValue(2);
        System.out.println("ta equals tb = " + ta.equals(tb));
        System.out.println("ta equals ta = " + ta.equals(ta));
        System.out.println("below will show other way of equals");
        Cube ca = new Cube(1.1,2.2,5.0);
        Cube cb = new Cube(1.1,2.2,5.0);
        Cube cc = new Cube(1.1,2.2,7.0);
        System.out.println("ca equals ta = " + ca.equals(ta));//跨类做了equals
        System.out.println("ca equals cc = " + ca.equals(cc));
        System.out.println("ca equals cb = " + ca.equals(cb));
    }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值