import java.io.Serializable;
import java.util.Objects;
/**
* 联合主键类 必须实现Serializable接口
* 重新equals()和hasCode()方法
*
* @author wxl
*
*/
public class ScoreId implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private int stuId; //学生id
private int subjectId;//科目编号
public int getStuId() {
return stuId;
}
public void setStuId(int stuId) {
this.stuId = stuId;
}
public int getSubjectId() {
return subjectId;
}
public void setSubjectId(int subjectId) {
this.subjectId = subjectId;
}
/**
* 重新hashCode方法
*/
@Override
public int hashCode() {
return Objects.hash(stuId,subjectId);
}
/**
* 重写Object的equals方法
*
* java核心技术 第九版
* page 171
*
* 1.显示参数命名为otherObj,方法中需要将它转换成另一个叫做other的变量
*/
@Override
public boolean equals(Object otherObj) {
//2. 检查 this和otherObj是否指向同一个对象 优化语句
if(this == otherObj) { return true;}
//3. 检测otherObj是否为空 如果为null 返回false
if(otherObj == null) { return false;}
//4. 比较this 和 otherObj 是否属于同一个类,不是返回false
//如果equals 的语义在每个子类中有所改变,就使用getClass检查
if(getClass() != otherObj.getClass()) { return false;}
//如果所有的子类都拥有统一的语义,就是使用instanceof 检查
if(!(otherObj instanceof ScoreId)) { return false;}
//5. 将otherObj转化成相应的类类型变量
ScoreId other = (ScoreId) otherObj;
//6. 开始对所有的属性进行比较,使用 == 比较基本类型属性,
// 使用equals 比较对象属性,如果所有的属性都匹配返回true,否则返回false
return stuId == other.stuId
&& this.subjectId == other.subjectId;
}
}