
( 2011—2012学年 第 一 学期 )
课程名称:java程序设计 开课实验室:计算中心304 2011年 11月 4 日
| 年级、专业、班 | 学号 | 姓名 | 成绩 | |||||
| 实验项目名称 | 接口 | 指导教 师 | 尚振宏 | |||||
| 教师评语 |
教师签名: 年 月 日 | |||||||
目的:掌握Java中接口的概念
内容:
1.完成下面要求的程序
◆定义一个接口Shape,它含有一个抽象方法 int area( )
◆定义一个表示三角形的类Triangle,该类实现接口Shape。此类中有两个分别用于存储三角形宽度和高度的private成员变量int width和int height,在该类实现的方法area中计算并返回三角形的面积。
◆定义一个表示矩形的类Rectangle,该类实现接口Shape。此类中有两个分别表示矩形长度和宽度的成员变量int width和int height,在该类实现的方法area中计算并返回矩形的面积。
◆定义一个类ShapeTest,该类中有一个方法如下:
public static void showArea(Shape s){
}
在ShapeTest类中定义main函数,在main函数中创建Triang类的对象和Rectangle类的对象,并调用方法showArea两次以输出两个对象的面积。
◆思考:两次调用showArea方法时调用的area方法各是在哪个类中定义的方法?
二、要求
给出实验内容1的程序设计、实现和结果,并对结果进行分析。
1、程序设计步骤:
◆定义一个接口Shape,它含有一个抽象方法 int area( )
◆定义一个表示三角形的类Triangle,该类实现接口Shape。此类中有两个分别用于存储三角形宽度和高度的private成员变量int width和int height,在该类实现的方法area中计算并返回三角形的面积。
◆定义一个表示矩形的类Rectangle,该类实现接口Shape。此类中有两个分别表示矩形长度和宽度的成员变量int width和int height,在该类实现的方法area中计算并返回矩形的面积。
◆定义一个类ShapeTest,该类中有一个方法如下:
public static void showArea(Shape s){
}
在ShapeTest类中定义main函数,在main函数中创建Triang类的对象和Rectangle类的对象,并调用方法showArea两次以输出两个对象的面积。
◆ 分析程序运行过程,与所要设计的结果对比,得出实验结果。
2、程序代码:
// 定义一个接口Shape,它含有一个抽象方法 int area( )
interface Shape{ //接口Shape
int area();
}
class Triangle implements Shape{ //类Triangle三角形
private int width;
private int height;
public Triangle(int width,int height){
this.width=width;
this.height=height;
}
public int area(){
return this.width*this.height/2;
}
}
class Rectangle implements Shape{ //类Rectangle长方形
int width;
int height;
public Rectangle(int width,int height){
this.width=width;
this.height=height;
}
public int area(){
return this.width*this.height;
}
}
public class ShapeTest{
public static void showArea(Shape s){ // 成员方法
System.out.println("area="+s.area());
}
public static void main(String args[]){
Shape a= new Triangle(30,40); //创建 对象
System.out.print("Triangle ");
showArea(a);
Shape b= new Rectangle(10,20);
System.out.print("Rectangle ");
showArea(b);
}
}
3、程序实现:
结果分析:通过运用接口实现了两个类实现了一个接口,运用了接口当中的抽象方法将三角形类和矩形的面积计算得以实现,通过对象a创建用了showArea()函数输出了Triangle(30,40)的面积。同理,创建Shape的b,再调用showArea()函数输出Rectangle(10,20)的面积。
