我有一个基类Component,我有继承自这个类的ComponentA,ComponentB等类。我将组件存储在HashMap中,其中包含组件名称的键和组件的值。但是,如果我获得ComponentA的值并对其执行函数,则会将其视为Component类。是否需要将组件类型转换为ComponentA来执行ComponentA的方法,还是需要研究另一种存储组件的方法?
答案 0 :(得分:1)
你有一个类型为component的对象?
组件c = //某个组件
类型转换很简单,只是
ComponentA a =(ComponentA)c
答案 1 :(得分:1)
使用@Override注释确保实际覆盖基类的方法:
public class Component {
...
public void doSomething() {
...
}
}
public class ComponentA extends Component {
...
@Override
public void doSomething() {
...
}
}
你不应该做任何演员阵容。多态的一个好处是它允许您通过公共基类使用不同类的对象。当您需要基类没有概念的派生类中的功能时,可以使用强制转换。使用强制转换来通过基类暴露的功能只会失去这种好处。
答案 2 :(得分:1)
如果您将ComponentA
作为Component
存储在地图中,那么您的对象仍为ComponentA
。在这种情况下,您可以进行类型转换,但我建议将实例类型检查为打击:
Component element = map.get(componentKey);
if(element instanceOf ComponentA){
ComponentA elementA = (ComponentA)element;
//use the elementA
elementA.doSomething();
}else if (element instanceOf ComponentB){
ComponentB elementB = (ComponentB)element;
//use the elementB
elementB.doSomething();
}
此外,如果您将所需方法从Component
覆盖到ComponentA
,则无需进行类型转换。正如我之前提到的,您的元素仍然是ComponentA
类型,因此将调用ComponentA
中的重写方法。
e.g。
public class Component{
public void printClass(){
System.out.println("This is class Component");
}
}
public class ComponentA{
@Override
public void printClass(){
System.out.println("This is class ComponentA");
}
}
Map<String, Component> map= new HashMap<String,Component>();
Component component = new ComponentA();
map.put("comp", component);
Component component1 = map.get("comp");
component1.printClass(); //<-- prints "This is class ComponentA"