实验八接口与多态
1.本实验的任务是设计和实现一个Soundable接口,该接口具有发声功能,同时还能调节声音的大小。Soundable接口的这些功能将会由三种声音设备来具体实现,他们分别是收音机Radio、随身听Walkman和手机Mobilephone。最后还要设计一个应用程序类来使用这些实现了Soundable接口的声音设备类。程序运行时,先询问用户想听哪种设备,然后程序就会按照该设备的工作方式来发出声音。
阅读并分析以下程序,将程序中的代码补充完整,编译并运行程序,查看结果。
//InterfaceTest.java
import java.util.Scanner;
interface Soundable {
public void increaseVolume( );
public void decreaseVolume( );
public void stopSound( );
public void playSound( );
}
class Radio implements Soundable {
public void increaseVolume( ) {
System.out.println("增大收音机音量");
}
public void decreaseVolume( ) {
代码1 //输出减小随身听音量
}
public void stopSound( ) {
System.out.println("关闭收音机");
}
public void playSound( ) {
System.out.println("收音机播放广播");
}
}
class Walkman implements Soundable {
public void increaseVolume( ) {
System.out.println("增大随声听音量"); }
public void decreaseVolume( ) {
System.out.println("减小随声听音量"); }
public void stopSound( ) {
System.out.println("关闭随声听");
}
public void playSound( ) {
System.out.println("随声听发出音乐"); }
}
class Mobilephone implements Soundable { public void increaseVolume( ) {
System.out.println("增大手机音量");
}
public void decreaseVolume( ) {
System.out.println("减小手机音量");
}
public void stopSound( ) {
System.out.println("关闭手机");
}
public void playSound( ) {
System.out.println("手机发出来电铃声"); }
}
class People {
private String name;
private int age;
public void listen(Soundable s) {
s.playSound( );
}
}
public class InterfaceTest {
public static void main(String[] args) {
int i;
People sportsman = new People( );
Scanner scanner = new Scanner(System.in);
代码2 //定义包含三个元素的接口变量数组//往声音设备数组中放入能发声的设备
soundDevice[0] = new Radio( );
soundDevice[1] = new Walkman( );
代码3 //创建手机对象并赋值给soundDevice[2] System.out.println("你想听什么? 请输入选择:0-收音机1-随声听2-手机");
i = scanner.nextInt( );
//开始听声音,调用People类的listen方法。
代码4
soundDevice[i].increaseVolume( );
代码5 //调用stopSound( )方法
}
}
2.卡车要装载一批货物,货物有3种商品:电视、计算机和洗衣机。要求计算出大货车和小货车各自所装载的3种货物的总重量。
要求有一个ComputeWeigth接口,该接口中有一个方法:
public double computeWeight(),有3个实现该接口的类:Television、Computer 和WashMachine。这3个类通过实现接口computerTotalSales给出自重。
有一个Car类,该类用ComputeWeight接口类型的数组作为成员,那么该数组的单元就可以存放Television对象的引用、Computer对象的引用或WashMachine对象的引用。程序能输出Car对象所装载的货物的总重量。
interface ComputerWeight
{
public double computeWeight();
}
class Television implements ComputerWeight
{ 【代码1】//实现computeWeight()方法设置Television的重量为43.8。}
class Computer implements ComputerWeight
{ 【代码2】//实现computeWeight()方法设置Computer的重量为76.5。}
class WashMachine implements ComputerWeight
{ 【代码3】//实现computeWeight()方法设置WashMachine的重量为133.5。
}
class Car
{ ComputerWeight[] goods;
double totalWeights=0;
Car(ComputerWeight[] goods)
{
this.goods=goods;
}
public double getTotalWeights()
{
totalWeights=0;
【代码4】//计算totalWeights
return totalWeights;
}
}
public class Road
{
public static void main(String args[])
{ ComputerWeight[] goodsOne=new ComputerWeight[50],
goodsTwo=new ComputerWeight[22] ;
for(int i=0;i