if(i%2==0)
goods[i]=newTelevision();
else
goods[i]=newWashMachine();
}
truck.setGoods(goods);
System.out.printf("货车装载的货物重量:
%-8.5fkg\n",truck.getTotalWeights());
}
}
3、实验结果
4、实验分析
接口回调是指:
可以把使用某一接口的类型创建的对象引用赋给该接口声明的接口变量中,那么该接口变量就可以调用被实现的接口中的方法,当接口变量调用被类实现的接口中的方法时,就是通知相应的对象调用接口的方法,这一过程成为对象功能的接口回调。
接口的方法不一定相同,接口回调可能产生不同的行为。
5、实验练习
请在实验基础上再编写一个实现ComputerWeight接口的类,比如Refrigerrator。
这样一来,货车装载的货物中就可以有Refrigerrator类型的对象。
当系统增加一个实现ComputerWeight接口的类后,Truck类需要进行修改吗?
答:
代码:
classRefrigerratorimplementsComputerWeight{
publicdoublecomputerWeight(){
return12.8;
}
}
实验三
1、实验题目
小狗在不同环境条件下可能呈现不同的状态表现,要求接口封装小狗的状态。
具体要求如下:
(1)编写一个接口DogState,该接口有一个名为voidshowState()方法。
(2)编写一个Dog类,该类中有一个DogState接口声明的变量state,另外,该类有一个show()方法,在该方法中让接口state回调showState()方法。
(3)编写若干个实现DogState接口的类,负责刻画小狗的各种状态。
(4)编写主类,在主类中实现测试小狗的各种状态。
2、程序代码
interfaceDogState{
publicvoidshowState();
}
classSoftlyStateimplementsDogState{
publicvoidshowState(){
System.out.println("听主人的命令");
}
}
classMeetEnemyStateimplementsDogState{
publicvoidshowState(){
System.out.println("狂叫,并冲过去狠咬敌人");
}
}
classMeetFriendStateimplementsDogState{
publicvoidshowState(){
System.out.println("晃动尾巴,表示欢迎");
}
}
classMeetAnotherdogStateimplementsDogState{
publicvoidshowState(){
System.out.println("嬉戏");
}
}
classDog{
DogStatestate;
publicvoidshow(){
state.showState();
}
publicvoidsetState(DogStates){
state=s;
}
}
publicclassCheckDogState{
publicstaticvoidmain(Stringargs[]){
DogyellowDog=newDog();
System.out.print("狗在主人面前:
");
yellowDog.setState(newSoftlyState());
yellowDog.show();
System.out.print("狗遇到敌人:
");
yellowDog.setState(newMeetEnemyState());
yellowDog.show();
System.out.print("狗遇到朋友:
");
yellowDog.setState(newMeetFriendState());
yellowDog.show();
System.out.print("狗遇到同类:
");
yellowDog.setState(newMeetAnotherdogState());
yellowDog.show();
}
}
3、实验结果
4、实验分析
面向接口编程是指当设计某种重要的类时,不让该类面向具体的类,而是面向接口,即所设计中的重要数据是接口声明的变量,而不是具体声明的对象。
5、实验练习
用面向接口的思想编写一个程序,模拟水杯中的水在不同温度下可能出现的状态。
代码:
interfaceWaterState{
publicvoidshowState();
}
classSubzeroStateimplementsWaterState{
publicvoidshowState(){
System.out.println("结冰");
}
}
classNormalStateimplementsWaterState{
publicvoidshowState(){
System.out.println("冰冷或凉快");
}
}
classHotStateimplementsWaterState{
publicvoidshowState(){
System.out.println("有热气冒出,温热");
}
}
classBoiledStateimplementsWaterState{
publicvoidshowState(){
System.out.println("沸腾,烫");
}
}
classWater{
WaterStatestate;
publicvoidshow(){
state.showState();
}
publicvoidsetState(WaterStates){
state=s;
}
}
publicclassCheckWaterState{
publicstaticvoidmain(Stringargs[]){
WatercupWater=newWater();
System.out.print("水杯中的水在零下时:
");
cupWater.setState(newSubzeroState());
cupWater.show();
System.out.print("水杯中的水在常温时:
");
cupWater.setState(newNormalState());
cupWater.show();
System.out.print("水杯中的水在六十七度时:
");
cupWater.setState(newHotState());
cupWater.show();
System.out.print("水杯中的水在一XX时:
");
cupWater.setState(newBoiledState());
cupWater.show();
}
}