Java实验报告4 接口和多态 下载本文

内容发布更新时间 : 2024/5/18 23:28:39星期一 下面是文章的全部内容请认真阅读。

1.接口A有一个f(int a, int b)方法

2. B类实现接口A,重写f()方法,返回最大公约数;

3. C类实现接口A ,重写f()方法,返回最小公倍数; 最小公倍数=(a*b)/最大公约数

4. D类提供show(A a)方法,以接口A的变量为参数,在方法内,打印出a.f(4,6)方法的返回值;

5. 设计test类,包含main函数,用D类生成对象,对象调用show()方法分别以B类对象作为参数和以C类对象作为参数,求最大公约数和最小公倍数! public int f(int a,int b) { //求最大公约数 int r =1 ;

int aa = a; int bb = b;

while (r!=0){ r = aa % bb; aa = bb; bb = r; } return aa;

}} 代码: interface A{ int f(int a,int b); }

class B implements A{ public int f(int a,int b){

int r =1 ;

int aa = a; int bb = b;

while (r!=0){ r = aa % bb; aa = bb; bb = r; } return aa; } }

class C implements A{ public int f(int a,int b){

int r =1 ;

int aa = a; int bb = b;

while (r!=0){ r = aa % bb; aa = bb; bb = r; } return a*b/aa; } } class D{

public void show(A a){System.out.println(a.f(4,6));} }

public class test{

public static void main(String args[]){ } }

D ss=new D(); B pp=new B(); C qq=new C(); ss.show(pp); ss.show(qq);

实验三:设计一个给班级学生成绩排序的程序,具体要求如下:

(1) 定义一个学生类student,包含姓名和分数两个属性:String name;int

score;

(2) 在主类中,定义一个学生类数组stu[ ],包含至少5个学生,对每个学

生的姓名和分数进行赋值;

(3) 对所有学生按照分数进行排序,并放入stu数组中;注意:如何排序,

方法不定,请同学们思考。

(4) 把所有学生信息,按照分数从高到底打印出来。

代码:

class student { }

public class test{

public static void main(String args[]){

student[] stu=new student[5]; student s1=new student(\,78); student s2=new student(\,68); student s3=new student(\,71); student s4=new student(\,83); student s5=new student(\,90); stu[0]=s1; stu[1]=s2; stu[2]=s3; stu[3]=s4; stu[4]=s5;

for(int j=0;j<=4;j++)

for(int k=4;k>j;k--){ }

if(stu[k].score>stu[k-1].score){ }

int temp=stu[k].score; stu[k].score=stu[k-1].score; stu[k-1].score=temp; String txt=stu[k].name; stu[k].name=stu[k-1].name; stu[k-1].name=txt;

String name; int score;

student(String ss,int pp){ }

this.name=ss; this.score=pp;

for(int i=0;i<=4;i++){

}

}

System.out.println(stu[i].name+\+stu[i].score);

}

【小结或讨论】

这次的实验内容为接口与多态,首先回顾了上节课继承的使用方法,然后又继续上次抽象类的讲解,接着是接口的使用规则,对比了类和接口的区别以及抽象类和接口的区别,实验的最后又简单介绍了数组和枚举的应用,接着,通过一系列的题目进行了巩固。