【问题标题】:How to implement two method with same name and different return type? [closed]如何实现两个具有相同名称和不同返回类型的方法? [关闭]
【发布时间】:2012-05-20 09:38:53
【问题描述】:

我想知道是否可以实现这样的代码?

public interface A {
public void execute();
}

public interface B { 
    public String execute(); 
}

class C implements A, B {
}

【问题讨论】:

  • 你试过了吗?
  • 抱歉类 B 的代码是这样的,public interface B { public String execute(); }
  • 业主可以编辑问题。
  • 我觉得这里很有趣..你懒得在这里问一个问题,而不是在你自己的机器上尝试几行代码..lol

标签: java interface return


【解决方案1】:

没有。这是不允许的,因为编译器无法判断您要使用哪个版本的execute。

如果你想重载方法,你需要改变方法参数,例如:

公共无效执行(); 公共字符串执行(int someParam);

【讨论】:

    【解决方案2】:

    不,你不能。

    JLS 要求每个方法具有不同的签名:

    JLS 8.4 - “类的主体将两个具有重写等效签名的方法声明为成员(第 8.4.2 节)是编译时错误。”

    其中 8.4.2 将 覆盖等效签名指定为在类型擦除后具有相同方法名称和相同参数类型的方法签名。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-19
      • 2013-02-28
      • 1970-01-01
      • 2019-04-29
      • 2015-03-11
      • 2022-01-22
      • 1970-01-01
      • 2022-06-10
      相关资源
      最近更新 更多