1.定义一个接口 Talkable(可通话的),接口内定义一个 call (打电话) 方法 2.定义一个类 ElderlyPhone (老年手机)实现 Talkable接口 3.定义一个接口 GamePlayable(可玩游戏的),接口内定义一个 playGame 方法 4.定义一个抽象类 PlayStation(游戏机)实现 GamePlayable接口 5.定义一个类HandheldPlayStation(掌上游戏机),从PlayStation类继承,实现 playGame 方法somatic 6.定义一个类SomaticPlayStation(体感游戏机),从PlayStation类继承,实现 playGame 方法somatic 7.定义一个类Smartphone(智能手机)实现 Talkable接口 以及 GamePlayable接口,实现call 和 playGame 方法 要求: 1.按照以上描述画出UML类图 2.main方法中 创建一个列表 ArrayList 放入几个HandheldPlayStation、SomaticPlayStation或Smartphone的对象,遍历列表,若对象可通话,调用其call方法。
时间: 2024-04-09 10:32:30 浏览: 113
以下是根据您的要求绘制的UML类图:
```
+------------------------+
| Talkable |
+------------------------+
| +call() |
+------------------------+
^
|
|
|
+------------------------+
| ElderlyPhone |
+------------------------+
| +call() |
+------------------------+
^
|
|
|
+------------------------+
| GamePlayable |
+------------------------+
| +playGame() |
+------------------------+
^
|
|
|
+------------------------+
| PlayStation |
+------------------------+
| +playGame() |
+------------------------+
^ ^
| |
| |
| |
+------------------------+
| HandheldPlayStation |
+------------------------+
| +playGame() |
+------------------------+
^ ^
| |
| |
| |
+------------------------+
| SomaticPlayStation |
+------------------------+
| +playGame() |
+------------------------+
^ ^
| |
| |
| |
+------------------------+
| Smartphone |
+------------------------+
| +call() |
| +playGame() |
+------------------------+
```
下面是一个示例的Java代码,实现了上述要求:
```java
import java.util.ArrayList;
interface Talkable {
void call();
}
class ElderlyPhone implements Talkable {
public void call() {
System.out.println("Calling from Elderly Phone");
}
}
interface GamePlayable {
void playGame();
}
abstract class PlayStation implements GamePlayable {
public void playGame() {
System.out.println("Playing game on PlayStation");
}
}
class HandheldPlayStation extends PlayStation {
public void playGame() {
System.out.println("Playing game on Handheld PlayStation");
}
}
class SomaticPlayStation extends PlayStation {
public void playGame() {
System.out.println("Playing game on Somatic PlayStation");
}
}
class Smartphone implements Talkable, GamePlayable {
public void call() {
System.out.println("Calling from Smartphone");
}
public void playGame() {
System.out.println("Playing game on Smartphone");
}
}
public class Main {
public static void main(String[] args) {
ArrayList<GamePlayable> devices = new ArrayList<>();
devices.add(new HandheldPlayStation());
devices.add(new SomaticPlayStation());
devices.add(new Smartphone());
for (GamePlayable device : devices) {
if (device instanceof Talkable) {
Talkable talkableDevice = (Talkable) device;
talkableDevice.call();
}
}
}
}
```
在上面的示例中,我们创建了一个`devices`列表,其中包含了`HandheldPlayStation`、`SomaticPlayStation`和`Smartphone`的对象。然后,我们遍历该列表,并检查每个对象是否可通话。如果是可通话对象,则调用其`call()`方法。
输出结果为:
```
Calling from Smartphone
```
这是因为`Smartphone`类实现了`Talkable`接口,并且它是列表中唯一一个可通话的对象。
阅读全文