两个类
1 :
public class Citizen{
String id;
String name;
int age;
public Citizen(String id,String name,int age){
this.id = id;
this.name = name;
this.age = age;
}
public Citizen(){}
public boolean equals(Object o){
if(o==null)
return false;
if(o.getClass()!=this.getClass())
return false;
if(this==o)
return true;
Citizen c = (Citizen)o;
return (this.id.equals(c.id));
}
public void test(){
}
}
2
public class TestC{
public static void main(String[] args){
Citizen c1 = new Citizen("a111111","zhangsan",30);
Citizen c2 = new Citizen("a111111","zhangsan",30);
System.out.println(c1.equals(c2));
}
}
通过testc调用citizen citizen里的equals为覆盖方法 ,我想问为什么equals里面还要把o转换成citizen类型的 c2不是在testc里面创建成citizen类的对象了么。。然后传过去还是citizen的啊 难道是因为形参是object类的? 但是equals里面也有判断啊,判断o传过来是不是citizen的 如果不是就直接返回了啊 ,那就证明他是,既然是为什么还要强转? |