1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
public class Person extends Object{
private String name;
private int age;
public Person(){}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
//重写父类的方法toString()
public String toString(){
return name + age;
}
//重写equals方法,比较两个对象的属性是否相同
public boolean equals(Object obj){
if( this == obj){
return true;
}
//对参数obj,非null判断
if( obj == null){
return false;
}
if( obj instanceof Person){
// 参数obj接受到是Person对象,才能转型
// 对obj参数进行类型的向下转型,obj转成Person类型
Person p = (Person)obj;
return this.age == p.age;
}
return false;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
//测试代码
public class TestEquals {
public static void main(String[] args) {
Person p = new Person("zhangsan",20);
Person p2 = new Person("lisi",20);
System.out.println(p.equals(p2)); //输出:true
}
}
|