[英]How can I assign an interface variable to a sub-interface variable?
我有這些接口:
public interface Interface {
int functionOne();
}
public interface SubInterface extends Interface {
String functionTwo();
}
和這個類:
public class MyClass implements SubInterface {
...
}
現在問題來了:
Interface a = new MyClass();
SubInterface b = a;
我想將a正在尋址的 MyClass 實例分配給變量b 。 我不想創建一個相同的實例,只需將現有的地址從a轉移到b ,但如果我這樣做,netbeans 會給我一個關於不兼容類型的錯誤。 我該怎么做?
當前,您的代碼將無法編譯,因為a
是Interface
類型並且不能分配給SubInterface
類型的變量。 因此你需要做:
SubInterface b = (MyClass)a;
如果你考慮一下; 這是完全SubInterface
因為並非每個實現類型的Interface
實現SubInterface
。
如果您不知道實現類的實際類型,則可以執行以下操作:
SubInterface b = (SubInterface) a;
這更安全。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.