java中instanceof和getClass()的区别分析
class A { }
class B extends A { }
Object o1 = new A();
Object o2 = new B();
o1 instanceof A => true
o1 instanceof B => false
o2 instanceof A => true // <================ HERE
o2 instanceof B => true
o1.getClass().equals(A.class) => true
o1.getClass().equals(B.class) => false
o2.getClass().equals(A.class) => false // <===============HERE
o2.getClass().equals(B.class) => true
getClass() will be useful when you want to make sure your instance is NOT a subclass of the class you are comparing with.
一个非常完美的equals方法的写法:
public boolean equals(Object otherObject)
{
// a quick test to see if the objects are identical
if (this == otherObject) return true;
// must return false if the explicit parameter is null
if (otherObject == null) return false;
// if the classes don't match, they can't be equal
if (getClass() != otherObject.getClass()) return false;
// now we know otherObject is a non-null Employee
Employee other = (Employee) otherObject;
// test whether the fields have identical values
return name.equals(other.name) && salary == other.salary && hireDay.equals(other.hireDay);
}
相关文章
基于Spring BeanUtils的copyProperties方法使用及注意事项
这篇文章主要介绍了基于Spring BeanUtils的copyProperties方法使用及注意事项,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-06-06IDEA安装lombok插件设置Enable Annotation Processing后编译依然报错解决方法
这篇文章主要介绍了IDEA安装lombok插件设置Enable Annotation Processing后编译依然报错解决方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2020-04-04IDEA 服务器热部署图文详解(On Update action/On frame deactivation)
这篇文章主要介绍了IDEA 服务器热部署详解(On Update action/On frame deactivation),本文通过图文并茂的形式给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2023-03-03springboot中使用mybatisplus自带插件实现分页的示例代码
这篇文章主要介绍了springboot中使用mybatisplus自带插件实现分页,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2022-09-09
最新评论