private HashMap<String, SuperClass> mapOfRoles = new HashMap();
public void X()
{
mapOfRoles.put(String, SubClassA);
mapOfRoles.put(String, SubClassB);
}
错误:找不到 put(String,Wolf) 的合适方法 playerRolesMap.put(listOfPlayers.get(0), new Wolf(listOfPlayers.get(0))); 方法 HashMap.put(String,Role) 不适用 (实参Wolf无法通过方法调用转换转换为Role)
其中 Wolf 是 Role 的子类
我正在尝试编写一个程序,我需要访问写入子类的方法,但是这不会编译,因为子类无法转换回父类(super class),编译器说:实际参数 subclassA 不能是通过方法调用转换转换为父类(super class))
目前我看不到另一种方法来实现我的代码以便能够动态检索对象。大多数时候,子类调用的方法都包含在父类(super class)中,但是每个子类都有一些仅与其相关的方法。
是否存在可以纠正的设计缺陷。
最佳答案
当然是你can do what you are trying 。但是,您应该将 String
和 SubClass1
和 SubClass2
的实例放入 map 中。
关于java - 将 HashMap 与子类一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14459510/