如何调用具有接口作为参数的方法?

时间:2013-03-14 16:25:58

标签: java

我在课堂上有以下方法:

public void Process(Measurable x)
{
    String y = x.getResult();

    for (int k = 0; k<item.length; k++)
    {
        if (y.equals(item[k])) tally[k]++;
    }
}

我的问题是,如何调用Process方法?用

调用它
Process(Measurable y);

在默认构造函数中或驱动程序类不起作用,也没有调用它没有参数(正如我所料)。

6 个答案:

答案 0 :(得分:2)

// How to call your Process method
Measureable y = new ConcreteMeasureable()
Process(y);

// Assuming you have something like this... 
class ConcreteMeasureable implements Measureable
{
    @Override
    public String getResult()
    {
        return "something here";
    }
}

答案 1 :(得分:1)

使用实现Process接口的类的实例调用Measurable方法;即使是anonymous class也可以。

答案 2 :(得分:1)

您可以使用实现Measurable接口的类来调用它。例如:

假设您有班级:

class Foo implements Measurable {
    @Overrride
    public String getResult(){ return "bar"; }
}

然后你可以这样打电话给Process

Process(new Foo());

这利用了一种名为Polymorphism的面向对象编程思想。

人们还提到你可以这样使用anonymous inner class

Process(new Measurable(){
    @Override
    public String getResult() {
        return "hey!";
    }
});

答案 3 :(得分:1)

您需要创建一个实现Measurable的对象:

public class Test {
  public static void main(String args[]) {
    new Test().test();
  }

  public interface Measurable {
    String getResult();
  }

  // Here to make `Process` compile.
  String[] item;
  int[] tally;

  public void Process(Measurable x) {
    String y = x.getResult();

    for (int k = 0; k < item.length; k++) {
      if (y.equals(item[k])) {
        tally[k]++;
      }
    }
  }

  static class M implements Measurable {

    @Override
    public String getResult() {
      return "M";
    }

  }

  public void test() {
    // Create an Object on the fly that implements Measurable (in a rather silly way).
    Process(new Measurable() {

      @Override
      public String getResult() {
        return "Hello";
      }

    });
    // Do it a bit more normally.
    Process(new M());
  }
}

答案 4 :(得分:0)

您可以使用polymorphism将实现该接口的对象视为接口类型,即使您无法直接实例化其对象。

例如,如果Measurable是一个接口,我们有一个这样的类:

public class MeasuredObject implements Measurable {
    ...
}

然后我们可以执行以下操作:

MeasuredObject object = new MeasuredObject();
Measurable measurableObject = (Measurable) object;

这应该表明可以调用你的方法。

Process(measurableObject);

虽然不需要显式类型转换,但它应该有助于说明这个概念。

(小方注意:考虑遵守Java编码标准并将方法名称改为camelCase。这会使您的代码更具可读性。)

答案 5 :(得分:0)

尝试类似:

public class Driver {
    public static void main(String...args) {
        Driver driver = new Driver();
        Foo foo = new Foo();
        driver.process(foo);
    }

    public void process(Measurable x) {
        String y = x.getResult();

        for (int k = 0; k<item.length; k++) {
            if (y.equals(item[k])) tally[k]++;
        }
    }

    private class Foo implements Measurable {
        String getResult() {
            /* Do stuff */
        }
    }

    public interface Measurable {
        String getResult();
    }
}

在某处还有yitemtally

P.S。在Java中,方法名称通常较低。