Java-具有相同方法的不同对象的数组
问题内容:
我正在练习继承。
我有两个相似的类,我想将其同化为一个数组,因此我想将Object类用作超类,因为所有内容都是Object的子类。
因此,例如,我将T类和CT类放入一个名为all的数组中,如下所示:
Object all[] = new Object[6];
all[0] = T1;
all[1] = CT2;
all[2] =T3;
all[3] = CT1;
all[4] = T2;
all[5] = CT3;
我跳过了声明,因为那不是我的问题。
当我希望使用循环在数组内调用函数时,我真正的问题就变成了:
for (int i = 0; i < 6; i++) {
all[i].beingShot(randomNum, randomNum, AK47.getAccuracy());
}
T和CT分别涉及的类都具有beingShot方法,该方法是公共的。
Eclipse建议将它们强制转换为快速修复。我想知道是否除了创建自己的拥有beingShot方法的Object类或将其添加到Object类之外,还有其他逻辑选择,尽管我觉得从长远来看,这些选择中的任何一个都会引起更多问题。
谢谢!
问题答案:
如果两个类都实现相同的方法,则应考虑创建一个interface
。
接口非常强大且易于使用。
您可以调用界面Shootable
。
您可以创建一个不同的对象数组,这些对象实现 Shootable 并一视同仁。
// Define a VERY simple interface with one method.
interface Shootable {
public void beingShot();
}
// Any class that implements this interface can be treated interchangeably
class Revolver implements Shootable {
public void beingShot() {
System.out.println("Revolver: firing 1 round");
}
class MachineGun implements Shootable {
public void beingShot() {
System.out.println("Machine Gun: firing 50 rounds");
}
}
class HockeyPuck implements Shootable {
public void beingShot() {
System.out.println("Hockey Puck: 80 MPH slapshot");
}
}
class RayBourquePuck implements Shootable {
public void beingShot() {
System.out.println("Hockey Puck: 110 MPH slapshot");
}
}
class OunceOfWhiskey implements Shootable {
public void beingShot() {
System.out.println("Whiskey Shot: 1 oz down the hatch...");
}
}
// You can declare an array of objects that implement Shootable
Shootable[] shooters = new Shootable[4];
// You can store any Shootable object in your array:
shooters[0] = new MachineGun();
shooters[1] = new Revolver();
shooters[2] = new HockeyPuck();
shooters[3] = new OunceOfWhiskey();
// A Shootable object can reference any item from the array
Shootable anyShootableItem;
// The same object can to refer to a MachineGun OR a HockeyPuck
anyShootableItem = shooters[0];
anyShootableItem.beingShot();
anyShootableItem = shooters[2];
anyShootableItem.beingShot();
// You can call beingShot on any item from the array without casting
shooters[0].beingShot();
shooters[1].beingShot();
// Let's shoot each object for fun:
for (Shootable s : shooters) {
s.beingShot();
}
这是一个很好的相关问答。