java中instanceof和getClass()的區(qū)別分析
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);
}
相關(guān)文章
Java后端限制頻繁請求和重復(fù)提交的實現(xiàn)
很多用戶會請求過于頻繁或者是多次重復(fù)提交數(shù)據(jù),本文主要介紹了Java后端限制頻繁請求和重復(fù)提交的實現(xiàn),文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-04-04解決mybatis執(zhí)行SQL語句部分參數(shù)返回NULL問題
這篇文章主要介紹了mybatis執(zhí)行SQL語句部分參數(shù)返回NULL問題,需要的的朋友參考下吧2017-06-06Spring?IOC容器基于XML外部屬性文件的Bean管理
這篇文章主要為大家介紹了Spring?IOC容器Bean管理XML外部屬性文件,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-05-05詳解SpringBoot注冊Windows服務(wù)和啟動報錯的原因
這篇文章主要介紹了詳解SpringBoot注冊Windows服務(wù)和啟動報錯的原因,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-03-03零基礎(chǔ)入門學(xué)習(xí)——Spring Boot注解(一)
這篇文章主要介紹了Spring Boot注解學(xué)習(xí)(一)要點,非常不錯,具有參考借鑒價值,需要的朋友參考下吧2017-05-05