给定如图所示的Player类及其子类MusicPlayer和VideoPlayer的继承关系UML图。其中,抽象类Player表示播放器,fileName是播放的文件,play()和stop()表示播放和停止方法;MusicPlayer表示音频播放器,volume表示音量,encodeAudio()表示音频解码;VideoPlayer表示视频播放器,duration表示视频持续时间,encodeVideo()表示视频解码。 (1)编写代码实现这些类,为这些类定义无参数构造方法,在构造方法中输出一句话,实现每个类中定义的方法。 (2)在main()方法中创建一个MusicPlayer对象,访问该对象的volume成员、play()与stopt()和encodeAudio()方法。访问toString()方法,该方法是在哪里定义的? (3)在main()方法中编写下面代码,该段代码是否有编译错误,为什么? Player player; MusicPlayer mplayer = new MusicPlayer(); mplayer.play(); player = mplayer; player.encodeAudio(); MusicPlayer mplayer2 = (MusicPlayer)player; player2.encodeAudio();
时间: 2023-11-27 21:54:34 浏览: 315
(1)代码实现如下:
```java
// Player类
public abstract class Player {
protected String fileName;
public Player() {
System.out.println("Creating a player...");
}
public abstract void play();
public abstract void stop();
@Override
public String toString() {
return "Player [fileName=" + fileName + "]";
}
}
// MusicPlayer类
public class MusicPlayer extends Player {
private int volume;
public MusicPlayer() {
super();
System.out.println("Creating a music player...");
}
public int getVolume() {
return volume;
}
public void setVolume(int volume) {
this.volume = volume;
}
@Override
public void play() {
System.out.println("Playing music...");
}
@Override
public void stop() {
System.out.println("Stopping music...");
}
public void encodeAudio() {
System.out.println("Encoding audio...");
}
}
// VideoPlayer类
public class VideoPlayer extends Player {
private int duration;
public VideoPlayer() {
super();
System.out.println("Creating a video player...");
}
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
@Override
public void play() {
System.out.println("Playing video...");
}
@Override
public void stop() {
System.out.println("Stopping video...");
}
public void encodeVideo() {
System.out.println("Encoding video...");
}
}
```
(2)在main()方法中的代码实现如下:
```java
public static void main(String[] args) {
MusicPlayer musicPlayer = new MusicPlayer();
musicPlayer.setVolume(50);
musicPlayer.play();
musicPlayer.stop();
musicPlayer.encodeAudio();
System.out.println(musicPlayer.toString());
}
```
toString()方法是在Object类中定义的,所有Java类都继承了Object类,因此MusicPlayer类也继承了toString()方法。
(3)代码中有编译错误,因为player2没有定义,应该改为mplayer2。另外,由于将Player类型的引用变量player指向了MusicPlayer对象,因此可以调用MusicPlayer类中定义的encodeAudio()方法,但是在将player转换为MusicPlayer类型的引用变量mplayer2时,需要进行强制类型转换,否则会出现编译错误。修改后的代码如下:
```java
public static void main(String[] args) {
Player player;
MusicPlayer mplayer = new MusicPlayer();
mplayer.play();
player = mplayer;
player.encodeAudio();
MusicPlayer mplayer2 = (MusicPlayer) player;
mplayer2.encodeAudio();
}
```
阅读全文