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

我正在练习inheritance。

我有两个类似的类,我想要同化为一个数组,所以我想使用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的类都有areShot方法,这是公开的。

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(); } 

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

对象没有方法beingShot。 如果数组中的所有对象都是同一个类,那么您的数组应该属于同一个类。 否则它们都应该实现相同的接口或扩展相同的类。 我无法想象你为什么要在这里显式扩展Object,它不会添加任何function。

您需要将object引用强制转换为适当的类来调用它们的方法。

对于从array获取的每个引用,您需要使用instanceof运算符进行检查,该运算符是对象引用引用的实例。因此,您可以对该类的引用进行类型转换。

但是Typecasting是一个丑陋的东西..你应该尽可能地避免它。如果你必须根据确切的子类选择调用哪个方法,你应该选择Interface ..这是你可以实现的最好方法你想要什么……

我认为你已经掌握了有关如何实施它的足够信息。

你不能这样做…因为Java不支持扩展方法。 (C#)

阅读下面的链接:

Java相当于C#扩展方法