java为什么我的equals方法不能识别对象变量?
我只是想写一个equals方法来比较学生的名字和部分。如果名称和节相同,那么equals方法应该打印为true。否则它应该打印错误
以下是我到目前为止的情况
public class Student {
private String name;
private int section;
public Student(String name, int section) {
this.name = name;
this.section = section;
}
public boolean equals(Object y) {
if (this.name.equals(y.name) && this.section.equals(y.section)) {
return true;
}
else {
return false;
}
}
}
错误是y.name
和y.section
。Eclipse告诉我name
和section
不能解析为字段
我的问题是,有谁能告诉我如何修改代码,这样我就可以使用。equals()方法
# 1 楼答案
你的
y
是任何Object
,不一定是Student
你需要像这样的代码
# 2 楼答案
您缺少向学生类输入cast对象