【发布时间】:2018-04-07 21:54:52
【问题描述】:
我的接口 (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);
}
}
我希望这能很好地解释这一点!
【问题讨论】:
-
请注意,这是向下转换,而不是向上转换。但听起来你想要泛型。
-
你无法避免向下转换,因为任何使用接口 A 使用你的 C 类的人都会认为 B 类的任何对象都可以传递给这个方法。如上所述,如果它们适合您的用例,您可以使用泛型。
-
就像@OliverCharlesworth 说的,对我来说听起来像是泛型
-
我认为你不需要强制转换,顺便说一下它是向下强制转换,在这种情况下,因为 C 必须实现 B 拥有的方法。所以,当你将 theObject 传递给 theMethod 时,并且没有声明新的引用即 theUpcastedObject,你可以直接使用它。
-
这里不需要泛型。正如@snr 所解释的,您只使用在接口 B 中声明的方法。因此,您的方法没有理由必须知道确切的实现类型。您对
theObject.srsly()的评论不正确。此方法在接口 B 中声明,因此您可以调用它。