我们了解到,在 Java 中,方法中只有一个 return 语句是一种很好的编码习惯。然而,这是我的问题;
我有一个抽象父类(super class),Action。有 WalkAction、JumpAction、DoNothingAction 等子类。Actor 类中有一个方法,可以根据 if-else if-else 循环中的要求返回一个操作。如果 Action 类无法实例化,我怎么可能只有 1 个 return 语句。现在该方法看起来像这样;
private Action getAction(Actor actor, Distance distance) {
if (distance < 5) {
return new JumpAction(actor);
}
else if (distance > 5 && distance < 10) {
return new WalkAction(actor);
}
else {
return new DoNothingAction(actor);
}
}
还显示没有 return 语句的错误
最佳答案
您可以将代码重写为以下单个return
表单:
private Action getAction(Actor actor, Distance distance) {
Action action;
if (distance < 5) {
action = new JumpAction(actor);
}
else if (distance > 5 && distance < 10) {
action = new WalkAction(actor);
}
else {
action = new DoNothingAction(actor);
}
return action;
}
或者:
private Action getAction(Actor actor, Distance distance) {
return
distance < 5 ? new JumpAction(actor) :
distance > 5 && distance < 10 ? new WalkAction(actor) :
new DoNothingAction(actor);
}
关于java - 方法中只有一个 return 语句,但对象无法实例化。无返回语句错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55944912/