小编Nze*_*zed的帖子

当对象 o 为空时,无法在 equals() 方法中返回 false。我已经添加了我的 equals() 实现以及测试用例

我的 equals() 方法:例如,当我的对象为 null 时,在第二个 if 语句中,我应该返回 false 但由于某种原因我的代码无法这样做。有什么帮助吗?

public boolean equals(Prof o) {

    boolean res = false;
    
    if(this == o) {
        res = true;
    }
    if(o == null || this.getClass() != o.getClass()) {
        res = false; 
    }
    Prof other = (Prof) o;
    if(this.year == other.year) { 
        if(this.id.equals(other.id)) {
            res = true; 
            }
    }
    else {
        res = false;
    }
    return res;   
}
Run Code Online (Sandbox Code Playgroud)

测试用例:

public void test02_ProfEqualHash() {

    Prof  p1 = new Prof("John S Lee", "yu213", 5);
     
    assertTrue(p1.equals(p1));
    
    Prof p0 …
Run Code Online (Sandbox Code Playgroud)

java oop junit compilation

0
推荐指数
1
解决办法
286
查看次数

标签 统计

compilation ×1

java ×1

junit ×1

oop ×1