【问题标题】:Single return statement in a method but object cannot be instantiated. No return statement error方法中的单个 return 语句,但无法实例化对象。没有返回语句错误
【发布时间】:2019-05-02 02:21:58
【问题描述】:

我们了解到,在 Java 中,一个方法中只有一个 return 语句是一种很好的编码习惯。但是,这是我的问题;

我有一个抽象超类,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 语句是一种很好的编码习惯。"我强烈反对。
  • @melpomene 好吧,问题是它也显示没有返回语句错误
  • 如果删除else {},错误会消失吗?
  • “它也显示没有返回语句的错误”我确定它不是!

标签: java return abstract


【解决方案1】:

您可以将代码重写为以下单个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);
}

【讨论】:

  • 我不能这样做,因为 Action 是一个抽象类,不能被实例化:/
  • @llamaro25 我的代码没有尝试实例化Action
  • 感谢您的帮助,我想我找到了解决方法。我首先初始化 Action action = new DoNothingAction(actor);然后我测试条件。因此,如果不满足任何条件,我将在最后返回操作
【解决方案2】:

从“if-else”块中添加“return null”。 编译器不知道您的运行时信息,可能整个“if-else”块 根本不匹配,然后您最终会出现“无返回语句”错误。

【讨论】:

    猜你喜欢
    • 2016-02-16
    • 2013-04-10
    • 2019-04-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-18
    • 2013-11-26
    • 2013-12-23
    • 1970-01-01
    相关资源
    最近更新 更多