我想编写一个方法来更改其他方法的return语句。例如,我有3种方法:
openCar
closeCar
isTheCarOpen:boolean
因此,如果用户调用方法openCar
然后调用方法isTheCarOpen
,则它应该返回true
。
public void openCar() {
System.out.println("Car has been opened");
}
public void closeCar() {
System.out.println("Car has been closed");
}
public boolean isTheCarOpen() {
return false;
}
答案 0 :(得分:5)
您不更改return语句。您更改方法返回的内容。在您的情况下,您想在类中代表门状态的布尔值(我们将其称为doorOpened
),并在调用openCar
和closeCar
方法时设置其值
class Car {
private boolean doorOpened;
public void openCar() {
doorOpened = true;
System.out.println("Car has been opened");
}
public void closeCar() {
doorOpened = false;
System.out.println("Car has been closed");
}
public boolean isTheCarOpen() {
return doorOpened;
}
}
答案 1 :(得分:1)
简单:您将字段添加到封闭的类中,例如:
public class Car {
private boolean doorOpen = false;
public boolean isDoorOpen() {
return doorOpen;
}
现在您可以使用所有不同的方法!
换句话说:您无需将方法的结果进行硬编码,只需将其“指向”周围环境类的“内部状态”即可。在这种情况下,您可能还拥有类似
的方法 public void openDoors() {
doorOpen = true;
}
使外界能够操纵该状态。
答案 2 :(得分:0)
使用适当的获取器/设置器在您自己的类中创建字段:
public class Car {
private boolean carOpen;
public void openCar() {
System.out.println("Car has been opened");
setCarOpen(true);
}
public void closeCar() {
System.out.println("Car has been closed");
setCarOpen(false);
}
public boolean isTheCarOpen() {
return carOpen;
}
public void setCarOpen(boolean carOpen){
this.carOpen = carOpen;
}
}
答案 3 :(得分:0)
boolean carOpen = false;
public void openCar() {
carOpen = true;
}
public void closeCar() {
carOpen = false;
}
public boolean isDoorOpen() {
return carOpen;
}