前言:
重写equals方法能够学习到多态、instanceof
代码实现:
public class Super{
public static void main(String[] args) {
Super.User1 user1 = new Super.User1();
Super.User2 user2 = new Super.User2();
System.out.println(user2.equals(user1));
}
interface IUser{
int number = 0;
String name = "里斯";
public void doing();
public void toDo();
}
static class User1 extends User2{
private int studentId = 1342432423;
private String studentClass = "二班";
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public String getStudentClass() {
return studentClass;
}
public void setStudentClass(String studentClass) {
this.studentClass = studentClass;
}
public void doing(){
System.out.println("User1类正在做");
}
public void toDo(){
System.out.println("User1类已经做过");
}
}
static class User2 implements IUser{
private int studentId = 1342432423;
private String studentClass = "二班";
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public String getStudentClass() {
return studentClass;
}
public void setStudentClass(String studentClass) {
this.studentClass = studentClass;
}
public void doing(){
System.out.println("User2类正在做");
}
public void toDo(){
System.out.println("User2类已经做过");
}
//使用Object的原因是它是所有类的父类,于是有了Obejct obj = new User1();把User1类向上转型为obj对象
public boolean equals(Object obj){
//如果比较的是自己本身
if(obj == this){
return true;
}
//考虑到程序的健壮性,在方法的形参是引用类型的时候,建议做非null处理
if(obj == null){
return false;
}
// 两个对象的类型都不一致,对象肯定不一致
if (getClass() != obj.getClass())
return false;
if(obj instanceof User2){
//将obj对象向下转型为User2类
User2 user = (User2) obj;
//这里添加我们想要判断的条件
if(this.getStudentClass().equals(user.getStudentClass()) && this.getStudentId() == user.getStudentId()){
//studentClass和studentId都相等的情况下
return true;
}
}
return false;
}
}
}
总结:
instanceof
左边必须是右边的类或者是子类的实现对象