程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> JAVA編程入門知識 >> java中instanceof和getClass()的區別分析

java中instanceof和getClass()的區別分析

編輯:JAVA編程入門知識

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

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved