[英]Java interface's method that uses another interface type
我的接口(A)中有一個方法可以接受另一個接口(B)作為參數。 當我去實現(A)並傳遞實現接口(B)的對象(C)時,我被困在向下轉換(B)到所傳遞對象的正確實現(C)上。
例如...
public interface A {
public void theMethod(B theObject);
}
public interface B {
public Properties jarJar();
public boolean isActuallyAJedi();
public void srsly();
}
public class C implements B {
//mumbo dumbo stuff from B
}
public class D implements A {
public void theMethod(B theObject) { // <------ I would prefer to explicitly define C as it is implementing B
C theUpcastedObject = (C) theObject; // <------ I want to avoid downcast here
theUpcastedObject.isActuallyAJedi();
theObject.srsly(); // <----- won't work because it is not aware of the implementation...
}
}
public class Main {
public static void main(String[] args) {
D stuffIWillDo = new D();
B theObject = new C(); // explicitly showing the implementation here...
D.theMethod(theObject);
}
}
我希望這能很好地解釋這一點!
實現接口B
的類C
不會覆蓋接口B
的方法。 我想您在這里想做的就是擴展接口B
但是類不能擴展接口。 您在這里可以做的是使C
成為接口B
擴展接口。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.