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 11:32:33 浏览: 103
以下是根据您的要求绘制的UML类图:
```
+------------------+
| Talkable |
+------------------+
| call() |
+--------+---------+
^
|
|
+--------+---------+
| ElderlyPhone |
+------------------+
| call() |
+--------+---------+
^
|
|
+--------+---------+
| GamePlayable |
+------------------+
| playGame() |
+--------+---------+
^
|
|
+--------+---------+
| PlayStation |
+------------------+
| playGame() |
+--------+---------+
^
|
+---------------+------------------+
| |
+---------------------+ +-------------------------+
| HandheldPlayStation | | SomaticPlayStation |
+---------------------+ +-------------------------+
| playGame() | | playGame() |
+---------------------+ +-------------------------+
^
|
|
+--------+---------+
| Smartphone |
+------------------+
| call() |
| playGame() |
+--------+---------+
```
以下是满足要求的Java代码示例:
```java
import java.util.ArrayList;
import java.util.List;
interface Talkable {
void call();
}
interface GamePlayable {
void playGame();
}
class ElderlyPhone implements Talkable {
public void call() {
System.out.println("Calling from Elderly Phone");
}
}
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) {
List<GamePlayable> gamePlayables = new ArrayList<>();
gamePlayables.add(new HandheldPlayStation());
gamePlayables.add(new SomaticPlayStation());
gamePlayables.add(new Smartphone());
for (GamePlayable gamePlayable : gamePlayables) {
if (gamePlayable instanceof Talkable) {
Talkable talkable = (Talkable) gamePlayable;
talkable.call();
}
}
}
}
```
这段代码创建了一个`ArrayList`,其中放入了`HandheldPlayStation`、`SomaticPlayStation`和`Smartphone`的对象。然后,通过遍历列表,如果对象实现了`Talkable`接口,就调用其`call()`方法。
阅读全文