[英]Java interface's method that uses another interface type
I have a method in my interface (A) that accepts another interface (B) as a parameter. 我的接口(A)中有一个方法可以接受另一个接口(B)作为参数。 When I go to implement (A) and pass an object (C) that implements interface (B), I am stuck downcasting (B) to the right implementation (C) of the passed object. 当我去实现(A)并传递实现接口(B)的对象(C)时,我被困在向下转换(B)到所传递对象的正确实现(C)上。
For example... 例如...
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);
}
}
I hope this explains this well! 我希望这能很好地解释这一点!
The class C
which implements the interface B
doesn't override the methods of interface B
. 实现接口B
的类C
不会覆盖接口B
的方法。 I guess what you are trying to do here is extending the interface B
. 我想您在这里想做的就是扩展接口B
But a class can't extend an interface. 但是类不能扩展接口。 What you can do here is make C
an interface which will extend interface B
. 您在这里可以做的是使C
成为接口B
扩展接口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.