我正在编写一个简单的平台游戏,我有几种类型的平台。我为最简单的类型创建了一个类,并创建了其余的子类,每个类之间的唯一区别是它们的变量值(因此它们都共享相同的变量和方法名称)。
在我的碰撞检测中,我循环遍历了一个HashMap
。在该 HashMap
中是每个类实例的 ArrayLists
。但是当我使用嵌套循环遍历尝试隐式调用它们的方法时,我发现如果不显式声明我想从哪个类调用方法,我就无法访问这些方法。
我做过研究,虽然我能看到这样做的唯一方法是分别循环遍历每个类的实例,这意味着每个类一个循环;我宁愿不这样做,因为它会比我认为需要的代码多得多。
最佳答案
为了能够在不同类型的类上调用通用方法,您需要为您的对象提供一个声明通用方法的通用父类(super class)型 - 即它们应该有一个通用父类(super class),或实现一个通用接口(interface)。
接口(interface)提供了一种声明通用功能的更简单方法,因为一个类可以实现多个接口(interface),但它只能扩展一个类。
提供一个带有通用方法的接口(interface),然后声明映射使用该接口(interface)的对象,即
interface CommonInterface {
void commonMethod(int arg);
}
class One implements CommonInterface {
public void commonMethod(int arg) {
...
}
}
class Two implements CommonInterface {
public void commonMethod(int arg) {
...
}
}
这是您现在可以做的:
Map<String,CommonInterface> myMap = new HashMap<>();
myMap.put("one", new One());
myMap.put("two", new Two());
for (Map.Entry<String,CommonInterface> e : myMap.entrySet()) {
System.out.println(e.getKey());
CommonInterface c = e.getValue();
c.commonMethod(123);
}
关于java - 不同类之间访问同一个方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34984320/