【问题标题】:Overloading Java Method from Inherited Interface从继承的接口重载 Java 方法
【发布时间】:2015-04-20 16:13:38
【问题描述】:

问题:

我有以下:

interface A 
{
    int MethodA(int x, int y);
}

interface B extends A
{
    //This is meant to overload MethodA
    int MethodA(int x, int y, int z);
}

当我尝试实现接口 B 并在 main 中运行该方法时,问题就来了。

class Foo implements B
{
    //For interface B
    public int MethodA(int x, int y, int z)
    {
        //Actual implementation
    }

    //For interface A
    public int MethodA(int x, int y)
    {
        //Actual implementation
    }
}

public static void main(String[] s)
{
    Foo foo = new Foo();
    //Problem occurs here
    foo.MethodA(1, 2, 3);
}

Eclipse 会抱怨说“类型 A 中的方法 MethodA(int, int, int) 不适用于参数 (int, int)。”

但是为什么呢?我已经实现了接口 B。MethodA(int, int, int) 不应该重载 MethodA(int, int),让 MethodA 也能接受三个整数吗?

【问题讨论】:

  • 在 Java 7 中为我工作,当然我已经纠正了给定代码中的所有编译错误(返回类型、公共修饰符、参数名称)
  • 这不是 Java 代码。这是纯文本。
  • 这里所谓的编译错误似乎不适用。也许该行打错了,应该是:A foo = new Foo();

标签: java overloading


【解决方案1】:

上面看起来有点混乱。

您需要指定返回类型,为每个参数指定名称(甚至在接口中)并将实现的方法声明为公共的,例如。

   public int MethodA(int a, int b, int c)
    {
        //Actual implementation e.g.
        return 0;
    }

您的静态 main() 方法必须驻留在一个类中(例如上面的 Foo 类),最后使用实参调用该方法。

一旦你这样做了,那么一切都应该很好。您当然可以像上面那样提供重载。您只需要先解决更基本的问题。我会得到一个非常基本的单一方法,然后从那里增强以使某些东西起作用。

【讨论】:

  • Once you've done that, then all should be good。不对。 foo.MethodA(int, int, int);呢?
  • 我错过了。谢谢你。这里这么有很多问题
  • 是的。在stackoverflow上看到这样的问题让我很头疼。但如果不回答,问题的质量只会越来越差。
  • 投反对票的人能否提供理由或撤销?
  • 很抱歉投了反对票,但答案仅涵盖了返回类型的问题,但在最初的几个版本中完全错过了方法参数和方法调用问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多