簡體   English   中英

將類實現接口傳遞給另一個構造函數實現相同的接口?

[英]Pass class implement interface into another constructor implement same 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);
        }   

我的1:

public class mine1 implements MyInterface { .... }

我的2:

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

MyInterface:

public interface MyInterface { }

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

有什么想法嗎,真的有什么問題嗎?

mine1.class.newInstance();

那里完全沒有必要,您需要實例化然后

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

請注意,Java類名稱以大寫字母開頭。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM