覆盖该方法

时间:2014-04-21 23:22:30

标签: java override

我被要求覆盖一个实现新行为的方法,我已经制作了构造函数和方法。

private String  name;
private boolean disease; 

public Area(Position pos, String name, boolean disease) {
    super(pos);

    this.name   = name;
    this.disease = disease;
}  

public String getName() {
    return name;
}

和我必须覆盖的方法,以便在药物充足的情况下可以在某个区域停止疾病

public boolean hasDisease() {
    return disease;
} 

我尝试使用

    if (medicine = true) { 
        disease = false
    } 
    return disease = true; 
}

但这导致其他测试失败。

2 个答案:

答案 0 :(得分:5)

您使用=代替==来测试相等性。

if(medicine == true) { // <-- Fixed this.
    disease = false
} 
    return disease = true; 
}

你可以更多地解决这个问题:

if(medicine)
    disease = false
return disease; 

答案 1 :(得分:0)

添加上面的答案

=是一个赋值运算符,所以说

int a = b;

a将取b的值。

其中as ==是比较运算符。

所以a == b实际上是一个函数调用,如果a和b具有相同的值,则返回布尔结果为true,否则返回false。对于基本类型,如int,double,Boolean,float等,它将比较值,对于复杂类型,如某个对象的实例(在大多数语言中),它将比较变量的内存位置。换句话说

String s = "This is True";
if(s == "This is True"){
    return true;
}   
return false;

永远不会返回true,因为s和&#34;这是真的&#34;不要驻留在内存中的相同位置。为此你需要使用

if(s.equals("This is True"){
    return true;
} 
return false;