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

Java-具有相同方法的不同对象的数组,第1张

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

如果两个类都实现相同的方法,则应考虑创建一个

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 interchangeablyclass 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 ShootableShootable[] 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 arrayShootable anyShootableItem;// The same object can to refer to a MachineGun OR a HockeyPuckanyShootableItem = shooters[0];anyShootableItem.beingShot();anyShootableItem = shooters[2];anyShootableItem.beingShot();// You can call beingShot on any item from the array without castingshooters[0].beingShot();shooters[1].beingShot();// Let's shoot each object for fun:for (Shootable s : shooters) {    s.beingShot();}

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



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5429302.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-11
下一篇 2022-12-11

发表评论

登录后才能评论

评论列表(0条)

保存