实验三—重写父类方法equals

import java.util.Scanner;
class Student {
int id;
String name;
int age;
public Student(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}

 /* 请在这里填写答案 */

}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Student s1 = new Student(sc.nextInt(),sc.next(),sc.nextInt());
Student s2 = new Student(sc.nextInt(),sc.next(),sc.nextInt());
System.out.println(s1.equals(s2));
sc.close();
}
}

我们需要在students类中重写equals方法,用equals方法判断学生学号是否相等,我们整理一下思路既然是equals方法需要比较学号大小那么返回类型一定就是布尔型,再加上public权限

public boolean equals(Object obj) {

if(obj instanceof Student){
Student p = (Student)obj;
return this.id == p.id;
}

//判断obj是否属于students类,如果是新建一个变量p,并将传入的obj强转成studens类,然后返回


if(this ==obj) {
return true;
}

//将引用与obj做比较,如果相同那么直接返回true

如果不属于一类则返回错误

public boolean equals(Object obj) {
if(obj instanceof Student){
Student p = (Student)obj;
return this.id == p.id;
}
if(this ==obj) {
return true;
}

else

return false;

}

发表评论

蜀ICP备2022010829号