设计和实现⼀个接⼝ 该接⼝能播放声⾳,调节声⾳的⼤⼩,接⼝的功能将由收⾳机(Radio)和⼿机(Mobilephone)两种设备来实现,最后设计⼀个应⽤程序类来 使⽤这些实现接⼝的声⾳设备。设计要求为当程序运⾏时先询问⽤户想使⽤哪个设备,然后程序按照该设备的⼯作⽅式来输出声⾳。
时间: 2024-02-27 18:55:03 浏览: 65
好的,我可以帮您设计这个接口和应用程序类。首先,我们定义一个 SoundPlayer
接口,包含播放声音和调节音量两个方法:
public interface SoundPlayer {
void playSound();
void adjustVolume(int volume);
}
然后,我们可以定义一个 Radio
类来实现该接口:
public class Radio implements SoundPlayer {
private int volume;
public Radio() {
this.volume = 50; // 默认音量为50
}
@Override
public void playSound() {
System.out.println("收音机播放声音");
}
@Override
public void adjustVolume(int volume) {
this.volume = volume;
System.out.println("收音机音量已调整为:" + volume);
}
}
同样地,我们可以定义一个 Mobilephone
类来实现该接口:
public class Mobilephone implements SoundPlayer {
private int volume;
public Mobilephone() {
this.volume = 50; // 默认音量为50
}
@Override
public void playSound() {
System.out.println("手机播放声音");
}
@Override
public void adjustVolume(int volume) {
this.volume = volume;
System.out.println("手机音量已调整为:" + volume);
}
}
接下来,我们可以定义一个应用程序类 SoundApp
,根据用户选择的设备来进行声音播放和音量调节:
import java.util.Scanner;
public class SoundApp {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请选择要使用的设备(1-收音机,2-手机):");
int choice = scanner.nextInt();
SoundPlayer player;
if (choice == 1) {
player = new Radio();
} else if (choice == 2) {
player = new Mobilephone();
} else {
System.out.println("无效的选择!");
return;
}
player.playSound();
System.out.println("请输入要调节的音量:");
int volume = scanner.nextInt();
player.adjustVolume(volume);
}
}
完整代码如下:
public interface SoundPlayer {
void playSound();
void adjustVolume(int volume);
}
public class Radio implements SoundPlayer {
private int volume;
public Radio() {
this.volume = 50; // 默认音量为50
}
@Override
public void playSound() {
System.out.println("收音机播放声音");
}
@Override
public void adjustVolume(int volume) {
this.volume = volume;
System.out.println("收音机音量已调整为:" + volume);
}
}
public class Mobilephone implements SoundPlayer {
private int volume;
public Mobilephone() {
this.volume = 50; // 默认音量为50
}
@Override
public void playSound() {
System.out.println("手机播放声音");
}
@Override
public void adjustVolume(int volume) {
this.volume = volume;
System.out.println("手机音量已调整为:" + volume);
}
}
import java.util.Scanner;
public class SoundApp {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请选择要使用的设备(1-收音机,2-手机):");
int choice = scanner.nextInt();
SoundPlayer player;
if (choice == 1) {
player = new Radio();
} else if (choice == 2) {
player = new Mobilephone();
} else {
System.out.println("无效的选择!");
return;
}
player.playSound();
System.out.println("请输入要调节的音量:");
int volume = scanner.nextInt();
player.adjustVolume(volume);
}
}
希望这个程序能够帮助您。