代码中包含两种重写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));
}
}