当前位置: 移动技术网 > IT编程>开发语言>Java > java中instanceof和getClass()的区别分析

java中instanceof和getClass()的区别分析

2019年07月22日  | 移动技术网IT编程  | 我要评论

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);
   }

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网