国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

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

2019-11-26 16:10:16
字體:
來源:轉載
供稿:網友

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 宜君县| 尚义县| 乌拉特前旗| 松溪县| 永仁县| 章丘市| 横峰县| 乌审旗| 庄浪县| 改则县| 芜湖县| 雅安市| 安阳市| 柞水县| 平阳县| 璧山县| 汤原县| 石渠县| 江山市| 禹城市| 四会市| 华坪县| 屏南县| 莱芜市| 本溪市| 双峰县| 乡城县| 北宁市| 宁海县| 岳西县| 胶南市| 新干县| 上思县| 谷城县| 贵阳市| 定西市| 泰宁县| 渑池县| 松溪县| 新民市| 鸡泽县|