[英]How to make a method change another method's return statement (boolean)
I want to write a method that changes the return statement of a different method. 我想编写一个更改其他方法的return语句的方法。 For example, I have 3 methods:
例如,我有3种方法:
openCar
closeCar
isTheCarOpen:boolean
So if a user calls the method openCar
and then calls the method isTheCarOpen
it should return true
. 因此,如果用户调用
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;
}
You don't change the return statement. 您无需更改return语句。 You change what the method returns.
您更改方法返回的内容。 In your case, you want to have a boolean in the class representing the state of the door (let's call it
doorOpened
) and you set its value when you call the openCar
and closeCar
method. 在您的情况下,您需要在表示门状态的类中具有一个布尔值(让我们将其
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;
}
}
Simple: you add a field to the enclosing class, like: 简单:您将一个字段添加到封闭的类中,例如:
public class Car {
private boolean doorOpen = false;
public boolean isDoorOpen() {
return doorOpen;
}
And now your different methods can all work with that! 现在,您可以使用所有不同的方法!
In other words: instead of hardcoding the result of that method, you simply "point" it to some "internal state" of the surrounding class. 换句话说:您无需将方法的结果硬编码 ,只需将其“指向”周围环境类的“内部状态”即可。 In this case, you might also have a method like
在这种情况下,您可能也有类似的方法
public void openDoors() {
doorOpen = true;
}
to enable the outside world to manipulate that state. 使外界能够操纵那个国家。
Create the fields in your own class with the proper getters/setters: 在您自己的班级中使用适当的获取器/设置器创建字段:
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;
}
}
boolean carOpen = false;
public void openCar() {
carOpen = true;
}
public void closeCar() {
carOpen = false;
}
public boolean isDoorOpen() {
return carOpen;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.