如何创建一个接口实例,以用作另一个类的参数'构造函数?

时间:2015-12-25 17:53:23

标签: java object interface

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

   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));
    }
}

1 个答案:

答案 0 :(得分:0)

您可以使用任何其他实现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));
   }
}