场景描述
阅读文章中一句话:如果在子类中重新定义equals,就要在其中包含调用 super.equals(other)。
自己测试
public class BaseEntity {
private String name;
String getMyName(){
return name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BaseEntity that = (BaseEntity) o;
return Objects.equals(name, that.name);
}
@Override
public int hashCode() {
return Objects.hash(name);
}
}
public class SysUser extends BaseEntity{
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
SysUser sysUser = (SysUser) o;
return Objects.equals(id, sysUser.id) &&
Objects.equals(createTime, sysUser.createTime) &&
Objects.equals(updateTime, sysUser.updateTime);
}
@Override
public int hashCode() {
return Objects.hash(super.hashCode(), id,createTime, updateTime);
}
}
子类调用 super.equals(o)
父类equals()如下:
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
>
BaseEntity that = (BaseEntity) o;
return Objects.equals(name, that.name);
}
得出结论(转载):
- super不是超类的引用,而是表示在子类中调用父类的方法或属性而已。
- 不管是BaseEntity的getClass()还是SysUser的getClass(),他们都是非覆盖式的从Object继承来的。
- 查阅了Object的getClass()方法的API,Object的getClass()方法的释义是:返回此 Object 的运行时类。返回的 Class 对象是由所表示类的 static synchronized 方法锁定的对象。
什么是运行时类,运行时类是Object的一个实例,注意了,关键来了,他返回的不是Object.class,他返回的是运行时类,就是虚拟机中是谁在运行就是谁,如果你new Date(),Date当然是运行时类,而不是Object,否则所有类的getClass()方法都返回了Object.class 了。
根据上一段解释,BaseEntity是Object的子类,BaseEntity.getClass()返回的肯定是BaseEntity.class,
同样的SysUser继承BaseEntity,假如有一个属于BaseEntity的getClass()他返回的也不可能是BaseEntity.class,因为当new SysUser()后,SysUser是一个运行时类,只不过他拥有BaseEntity的资源结构。所以谁被实例化,谁就是一个运行时类。 - 如果想要从SysUser中得到BaseEntity.class,可以用SysUser.getClass().getSuperClass();