【问题标题】:How do I create an instance of an interface to use as an argument to another class' constructor?如何创建接口的实例以用作另一个类的构造函数的参数?
【发布时间】:2015-12-25 17:53:23
【问题描述】:

我得到了类和一个接口。有一个类实现了接口,但同一个类使用接口的对象。

   public interface Function {

        public double eval(double valueIndependentVariable);
    }

public class PiecewiseFunction implements Function {

    private Function left;
    private Function right;
    private double boundary;

    public PiecewiseFunction(Function left, Function right, double boundary) {
        this.left = this.left;
        this.right = this.right;
        this.boundary = this.boundary;
    }

    @Override
    public double eval(double valueIndependentVariable) {
        if (valueIndependentVariable < boundary) {
            return left.eval(valueIndependentVariable);
        } else {
            return right.eval(valueIndependentVariable);
        }
    }

}

如您所见,使用了两个 Function 对象,但如果我想要一个 PiecewiseFunction 的实例,如何创建它们?

public class Functie {

    public static void main(String[] args){
        // how do I declare foo and bar?
        Function graad = new PiecewiseFunction(foo, bar, 33);
        System.out.println(graad.eval(26));
    }
}

【问题讨论】:

  • 你是什么意思我如何创建这些?就像任何其他对象一样。获取一个实现接口的类并实例化它。然后将实例的引用传递给您的 PiecewiseFunction 构造函数。
  • 我创建了一个可以用来实例化的类,但我得到了 NullPointerException..

标签: java object interface


【解决方案1】:

您可以使用任何其他实现 Function 的类:

class Foo implements Function
{
   private double boundary;

   public Foo(double boundary)
   {
      this.boundary = boundary;
   }

   @Override
   public double eval(double valueIndependentVariable)
   {
      // add implementation here
   }
}

所以您的示例可能如下所示:

public class Functie 
{

   public static void main(String[] args)
   {
       Function foo = new Foo(10.0);
       Function bar = new Foo(12.0);
       Function graad = new PiecewiseFunction(foo, bar, 33);
       System.out.println(graad.eval(26));
   }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-20
    • 1970-01-01
    • 2013-06-18
    • 2014-03-06
    相关资源
    最近更新 更多