我想將一個類實例傳遞給另一個類的方法,並確保它實現了所需的接口。該代碼是這樣的如何將實例傳遞給必須實現接口的類,然後在java中使用它?
public interface MyInterface{
someMethod();
}
public class A implements MyInterface{
B bInst;
public someMethod(){
//stuff
}
public bar(){
bInst = new B(this); // [4]
}
}
public class B{
private MyInterface x; //[1]
// here i don't want to use
void B(MyInterface y){ // [2]
this.x=y; // [3]
}
private void foo(){
x.someMethod();
}
}
我試着在[1] [2] subsituting 「MyInterface的」 「<類?擴展IBtBytesReciever>」,但是編譯器給我的錯誤,或者在[2]或[3 ]。
實現我的想法的最佳方式是什麼?
注:我不想因爲B類不需要知道類的確切名稱,直接使用A類和它必須是可重複使用的不同類別
編輯:錯誤是[ 4]
constructor B(class A) not defined
你不喜歡'void B(MyInterface y)'?它似乎完全符合你的意思.. – 2012-03-30 19:29:46
你得到的錯誤信息是什麼? – ControlAltDel 2012-03-30 19:30:39
編譯器錯誤是什麼? – Kashyap 2012-03-30 19:31:12