[改善Java代码]在equals中使用getClass进行类型判断
package com.question;
/**
* @author kankan
* @creater 2019-05-19 15:45
*/
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Person() {
}
public Person(String name) {
this.name = name;
}
@Override
public boolean equals(Object obj) {
if(obj instanceof Person){
Person p = (Person) obj;
// 将此 String 与另一个 String 比较,不考虑大小写
return name.equalsIgnoreCase(p.getName().trim());
}
return false;
}
}
package com.question;
/**
* @author kankan
* @creater 2019-05-19 15:46
*/
public class Employee extends Person{
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Employee(int id) {
this.id = id;
}
public Employee(String name, int id) {
super(name);
this.id = id;
}
@Override
public boolean equals(Object obj) {
if(obj instanceof Employee){
Employee e = (Employee) obj;
return super.equals(obj)&& e.getId() == id;
}
return false;
}
}
package com.question;
/**
* @author kankan
* @creater 2019-05-19 15:44
*/
public class Client {
public static void main(String[] args) {
Employee e1 = new Employee("张三",100);
Employee e2 = new Employee("张三",1001);
Person p1 = new Person("张三");
System.out.println(p1.equals(e1));
System.out.println(p1.equals(e2));
System.out.println(e1.equals(e2));
}
}
package com.question;
/**
* @author kankan
* @creater 2019-05-19 15:45
*/
public class Person {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Person() {
}
public Person(String name) {
this.name = name;
}
@Override
public boolean equals(Object obj) {
if(obj!=null && obj.getClass() == this.getClass()){
Person p = (Person) obj;
if(p.getName()==null || name==null){
return false;
}else{
return name.equalsIgnoreCase(p.getName());
}
}
return false;
}
}
package com.question;
/**
* @author kankan
* @creater 2019-05-19 15:46
*/
public class Employee extends Person{
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Employee(int id) {
this.id = id;
}
public Employee(String name, int id) {
super(name);
this.id = id;
}
@Override
public boolean equals(Object obj) {
if(obj !=null && obj.getClass() == this.getClass()){
Employee e = (Employee) obj;
return super.equals(obj)&& e.getId() == id;
}
return false;
}
}