欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-12-04 16:22:22
class a { }  class b extends a { }  object o1 = new a();  object o2 = n...

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