【案例介绍】
运行结果:
【案例目标】
- 学会分析“发声接口程序设计”实现的逻辑思路。
- 能够独立完成“发声接口程序设计”的源代码编写、编译及运行。
- 掌握接口的实现方式。
【案例分析】
(1)通过任务的描述可知,此程序包含了一个发声接口 Soundable,Soundable 接口的
有三个声音设备实现类实现了 Soundable 接口,分别是收音机类 Radio,随身听类 Walkman
和手机类 Mobilephon。
(2)Radio、Walkman 和 MobilePhon 这三个声音设备实现类需要分别实现 Soundable 接
口接口的相关功能。
(3)然后,还需设计一个应用程序类来使用这些实现 Soundable 接口的声音设备。
(4)最后编写测试类,在 main()方法中,编写程序,使用户可以自主选择要使用的设
备;创建使用设备的对象,根据用户选择的声音设备,调用相关方法,模拟使用声音设备对
应的功能。
【案例实现】
import java.util.Scanner;
import java.util.Scanner;interface Soundable {// 发出声音public void playSound();// 降低声音public void decreaseVolume();// 停止声音public void stopSound();
}class SampleDisplay {public void display(Soundable soundable) {soundable.playSound();System.out.println("您是否要降低音量?");System.out.println("1-是 2-否");Scanner scan = new Scanner(System.in);int choice = scan.nextInt();switch (choice) {case 1:soundable.decreaseVolume();break;case 2:break;default:System.out.println("请在可选择范围内选择!");}System.out.println("您是否要关机?");System.out.println("1-是 2-否");choice = scan.nextInt();switch (choice) {case 1:soundable.stopSound();break;case 2:break;default:System.out.println("请在可选择范围内选择!");}}
}class Radio implements Soundable {@Overridepublic void playSound() {System.out.println("收音机发出声音:滋滋滋~~~");}@Overridepublic void decreaseVolume() {System.out.println("已降低收音机音量");}@Overridepublic void stopSound() {System.out.println("已关闭收音机");}
}class Walkman implements Soundable {@Overridepublic void playSound() {System.out.println("随身听发出声音:铃铃~~~");}@Overridepublic void decreaseVolume() {System.out.println("已降低随身听音量");}@Overridepublic void stopSound() {System.out.println("已关闭随身听");}
}class MobilePhone implements Soundable {@Overridepublic void playSound() {System.out.println("手机发出来电铃声:叮当、叮当");}@Overridepublic void decreaseVolume() {System.out.println("已降低手机音量");}@Overridepublic void stopSound() {System.out.println("已关闭手机");}
}public class TestDemo {public static void main(String[] args) {System.out.println("你想听什么?请输入:");System.out.println("0-收音机 1-随身听 2-手机");Scanner scan = new Scanner(System.in);int choice = scan.nextInt();SampleDisplay sampleDisplay = new SampleDisplay();switch (choice) {case 0:Radio radio = new Radio();sampleDisplay.display(radio);break;case 1:Walkman walkman = new Walkman();sampleDisplay.display(walkman);break;case 2:MobilePhone mobilePhone = new MobilePhone();sampleDisplay.display(mobilePhone);break;default:System.out.println("请在可选择范围内选择!");break;}}
}