How to override equals method in Java

后端 未结 9 1785
自闭症患者
自闭症患者 2020-11-22 01:41

I am trying to override equals method in Java. I have a class People which basically has 2 data fields name and age. Now I want to ove

9条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 02:08

    @Override
    public boolean equals(Object that){
      if(this == that) return true;//if both of them points the same address in memory
    
      if(!(that instanceof People)) return false; // if "that" is not a People or a childclass
    
      People thatPeople = (People)that; // than we can cast it to People safely
    
      return this.name.equals(thatPeople.name) && this.age == thatPeople.age;// if they have the same name and same age, then the 2 objects are equal unless they're pointing to different memory adresses
    }
    

提交回复
热议问题