Java - 具有相同方法的不同对象的数组

ZAX*_*ZAX 3 java polymorphism inheritance casting interface

我正在练习继承.

我有两个类似的类,我想要同化为一个数组,所以我想使用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;
Run Code Online (Sandbox Code Playgroud)

我跳过了声明,因为那不是我的问题.

当我希望使用循环调用数组中的函数时,我的真正问题就变成了:

for (int i = 0; i < 6; i++) {

    all[i].beingShot(randomNum, randomNum, AK47.getAccuracy());
}
Run Code Online (Sandbox Code Playgroud)

涉及T和CT的类都分别具有isShot方法,该方法是公开的.

Eclipse建议将它们作为快速修复.我想知道除了创建我自己的持有beingShot方法的Object类,或者将其添加到Object类之外是否还有其他逻辑选择,尽管我觉得这些选择中的任何一个都会导致更长时间的问题.

谢谢!

jah*_*roy 12

如果两个类都实现相同的方法,则应考虑创建一个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();
}
Run Code Online (Sandbox Code Playgroud)

这是一个很好的相关问题和答案.