class Person { private String name ; private int age ; public Person(String name,int age) { this.name = name ; this.age = age ; } public String toString() { // 方法覆写 return "姓名:" + this.name + ",年龄:" + this.age ; } public boolean equals(Object obj) { if (this == obj) { //this指代当前调用equals()方法的对象 return true ; } if (obj == null) { return false ; } if (! (obj instanceof Person)) { // 不是本类对象 return false ; } Person per = (Person) obj ; // 为什么一定要强制类型转换,不转就错,想不通? if (this.name.equals(per.name) && this.age == per.age) { return true ; } return false ; } } public class TestDemo { public static void main(String args[]) { Person per1 = new Person("小王",20) ; Person per2 = new Person("小王",20) ; System.out.println(per1.equals("Hello")) ; System.out.println(per1.equals(per2)) ; } } |