我的接口(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);
}
}
我希望这能很好地解释这一点!
答案 0 :(得分:-1)
实现接口C
的类B
不会覆盖接口B
的方法。我想你在这里尝试做的是扩展接口B
。但是一个类不能扩展接口。你可以在这里做的是使C
接口扩展接口B
。