[英]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.