equals方法重写遇到的问题
class Person {
private String name;
private String location;
Person(String name) {
this.name = name;
location = "haerbin";
}
Person(String name,String location) {
this.name = name;
this.location = location;
}
public String Info() {
return "name:"+name+","+"location:"+location;
}
}
class Teacher extends Person {
private String job;
Teacher(String n,String j) {
this(n,"beijing",j);
}
Teacher(String name,String location,String job) {
super(name,location);
this.job = job;
}
public String Info() {
return super.Info()+","+"job:"+job;
}
}
public class TestEq {
public boolean equals(Object otherObject) {
if(this == otherObject) return true;
else {
if(otherObject == null) return false;
else {
if(this.getClass() != otherObject.getClass()) return false;
else {
if(otherObject instanceof Person) {
Person other = (Person)otherObject;
if(name == other.name && location == other.location) return true;
}
else {
if (otherObject instanceof Teacher) {
Teacher other = (Teacher)otherObject;
if(name == other.name && location == other.location && other.job == job)
return true;
}
}
}
}
return false;
}
}
public static void main(String[] args) {
Person p1 = new Person("leisao");
Person p2 = new Person("dachao","jilin");
Teacher t1 = new Teacher("jinfeng","gongwuyuan");
Teacher t2 = new Teacher("xiaogang","yunnan","yazi");
Teacher t3 = new Teacher("xiaogang","yunnan","yazi");
Teacher t4 = new Teacher("xiaogang","yunnan","yazi");
System.out.println(t3.equals(t4));
System.out.println(p1.Info());
System.out.println(p2.Info());
System.out.println(t1.Info());
System.out.println(t2.Info());
}
}