将类实现接口传递到另一个构造函数实现相同的接口?

时间:2015-11-04 09:51:06

标签: java javafx interface

无法找到与我相同的问题/问题,我尝试做的是将一个类作为参数传递给另一个也实现相同接口的类,请参阅下面的代码:

public class Combiner implements myInterface {

private final myInterface right;
private final myInterface left;

public Combiner(myInterface right, myInterface left) {
    this.right = right;
    this.left = left;
    System.out.println("In constructor");
}

来自另一个班级:

        try {
            MyInterface right = mine1.class.newInstance();
            MYInterface left = mine2.class.newInstance();
            Combiner comb = new Combiner(right, left);
        } catch (Exception e) {
            System.err.println(e);
        }   

mine1:

public class mine1 implements MyInterface { .... }

mine2:

public class mine2 implements MyInterface { ..... }

MyInterface的:

public interface MyInterface { }

获取:java.lang.InstantiationException:com.livingcode.workflow.parts.HotspotSelectionChoice

任何想法,真的错了吗?

1 个答案:

答案 0 :(得分:1)

mine1.class.newInstance();

那是完全不必要的,你需要像

那样
MyInterface right = new mine1();
MYInterface left = new mine2();
Combiner comb = new Combiner(right, left);

请注意,Java类名称以大写字母开头。