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);
}
上一篇: 详解vue2.0模拟后台json数据