JAVA第六次实验报告 接口

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

实验一

1、实验题目

体操比赛计算选手成绩的办法是去掉一个最高分和一个最低分再计算平均分,而学校考察一个班级的某科目的考试情况时,是计算全班学生的平均成绩。Gymnastics 类和School 类都实现了ComputerAverage接口,但实现方式不同。

2、程序代码

interface ComputerAverage{

public double average(double x[]);

}

class Gymnastics implements ComputerAverage{

public double average(double x[]){

int count=x.length;

double aver=0,temp=0;

for(int i=0;i

for(int j=i;j

if(x[j]

temp=x[i];

x[i]=x[j];

x[j]=temp;

}

}

}

for(int i=1;i

aver=aver+x[i];

}

if(count>2)

aver=aver/(count-2);

else

aver=0;

return aver;

}

}

class School implements ComputerAverage{

public double average(double x[]){

int count=x.length;

double aver=0;

for(int i=0;i

aver=aver+x[i];

}

if(count>0)

aver=aver/count;

return aver;

}

}

public class Estimator {

public static void main(String args[]){

double a[]={9.89,9.88,9.99,9.12,9.69,9.76,8.97};

double b[]={89,56,78,90,100,77,56,45,36,79,98};

ComputerAverage computer;

computer=new Gymnastics();

double result=computer.average(a);//computer调用average(double x[])方法,将数组a传递给参数x

System.out.printf("%n");

System.out.printf("体操选手最后得分:%5.3f\n",result);

computer=new School();

result=computer.average(b);//computer调用average(double x[])方法,将数组b 传递给参数x

System.out.printf("班级考试平均分数:%-5.2f\n",result);

}

}

3、实验结果

4、实验分析

一个类可以实现多个接口,类通过使用关键字implements声明自己实现一个或多个接口,如果一个非抽象类实现了某个接口,那么这个类必须重写该接口的所有方法。

5、实验练习

School类如果不重写public double aversge(double x[])方法,程序编译时提示怎样的错误?

答:SChool不是抽象的,并且未覆盖ComputerAverage中的抽象方法。

实验二

1、实验题目

货车要装载一批货物,货物由三种商品组成:电视、计算机和洗衣机,卡车需要计算出整批货物的重量。

2、实验代码

interface ComputerWeight{

public double computerWeight();

}

class Television implements ComputerWeight{

public double computerWeight(){

return 3.5;

}

}

class Computer implements ComputerWeight{

public double computerWeight(){

return 2.67;

}

}

class WashMachine implements ComputerWeight{

public double computerWeight(){

return 13.8;

}

}

class Truck{

ComputerWeight []goods;

double totalWeights=0;

Truck(ComputerWeight[] goods){

this.goods = goods;

}

public void setGoods(ComputerWeight[] goods){

this.goods = goods;

}

public double getTotalWeights(){

totalWeights=0;

for(int i=0;i

totalWeights = totalWeights + goods[i].computerWeight();

}

return totalWeights;

}

}

public class CheckCarWeight{

public static void main(String args[]){

ComputerWeight []goods = new ComputerWeight[650]; //装载650件货物for(int i=0;i

相关文档
最新文档