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

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

接口非常强大且易于使用.

你可以调用你的界面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();

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值