国产探花免费观看_亚洲丰满少妇自慰呻吟_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);
   }

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 蕉岭县| 肇东市| 中西区| 盐边县| 勐海县| 剑河县| 漳平市| 潜江市| 沛县| 井研县| 平舆县| 开封市| 都昌县| 肇州县| 安图县| 云浮市| 杂多县| 岑溪市| 卢龙县| 梁平县| 河北省| 鄂尔多斯市| 马公市| 汉沽区| 客服| 姜堰市| 湘阴县| 乳山市| 新化县| 邵阳县| 双鸭山市| 北票市| 翁源县| 徐州市| 囊谦县| 东台市| 九台市| 九台市| 枣强县| 若羌县| 蓬溪县|