1 //覆写Object.equals 2 class Demo { 3 private String name; 4 private int age; 5 public Demo(String name,int age) { 6 this.name=name; 7 this.age=age; 8 } 9 public String toString() { 10 return this.name+this.age; 11 } 12 public boolean equals(Object obj) { //覆写equals方法 13 if(obj==null) { //当传入的obj对象为null时 14 return false; 15 } 16 if (!(obj instanceof Demo)) { //当传入的obj对象为String数据类型或不是本类对象时 17 return false; 18 } 19 Demo dd = (Demo) obj; //强制向下转型,目的获取类中的属性 20 //此时需要比较两个对象,当前this 与 传入的Object 21 return this.name.equals(dd.name) && this.age == dd.age; 22 } 23 } 24 public class equalss { 25 public static void main(String[] args) { 26 Demo de1 = new Demo("李光",16); 27 Demo de2 = new Demo("李光",16); 28 System.out.println(de1.equals(de2)); 29 } 30 }