栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

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



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/453776.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号