用java设计一个soudable,该接口具有发声功能,还能调节音量大小,soundable接口可由三个设备实现,分别是收音机radio,随身听walman,手机Mobliephone
时间: 2024-11-23 09:39:00 浏览: 17
在Java中,你可以设计一个名为`Soundable`的接口,并添加`setVolume(int volume)`方法用于设置音量,同时让三个设备类`Radio`, `Walkman`, 和 `MobilePhone` 实现这个接口。下面是相关的代码实现:
```java
// Soundable 接口
public interface Soundable {
// 设置音量
void setVolume(int volume);
// 抽象方法,播放声音
abstract void playSound();
}
// Radio 类实现 Soundable 接口
public class Radio implements Soundable {
private int volume;
@Override
public void setVolume(int volume) {
this.volume = volume;
System.out.println("Radio set to volume: " + volume);
}
@Override
public void playSound() {
System.out.println("Radio is playing with volume: " + volume);
}
}
// Walkman 类实现 Soundable 接口
public class Walkman implements Soundable {
private int volume;
@Override
public void setVolume(int volume) {
this.volume = volume;
System.out.println("Walkman set to volume: " + volume);
}
@Override
public void playSound() {
System.out.println("Walkman is playing with volume: " + volume);
}
}
// MobilePhone 类实现 Soundable 接口
public class MobilePhone implements Soundable {
private int volume;
@Override
public void setVolume(int volume) {
this.volume = volume;
System.out.println("MobilePhone set to volume: " + volume);
}
@Override
public void playSound() {
System.out.println("MobilePhone is playing with volume: " + volume);
}
}
// 主程序
public class Main {
public static void main(String[] args) {
Soundable radio = new Radio();
radio.setVolume(50); // 设置音量
radio.playSound();
Soundable walkman = new Walkman();
walkman.setVolume(75);
walkman.playSound();
Soundable mobilePhone = new MobilePhone();
mobilePhone.setVolume(90);
mobilePhone.playSound();
}
}
```
阅读全文