Java上机实验6
实验六
实验时间:
实验班级:
指导老师:
实验名称:包、接口及异常处理。
实验目的:掌握包、接口的声明与使用,掌握异常的处理
实验要求:独立完成实验内容。
七、实验内容:
1、编写一个应用程序,实现以下功能:
①声明一个接口 Calculability ,接口中包含一个方法area 。
②声明一个三角形类继承该接口,类名为Triangle,类中包含两个变量、一个带参数年的构造方法和一个计算三角形面积的方法:
三角形的底边长w
三角形的高h
构造方法Triangle double width,double height 。
计算三角形面积的方法area ,该方法覆盖接口 Calculability 的同名方法,计算三角形的面积(w*h/2)。
③声明一个锥体类(Taper),包含一个接口对象bottom 锥体的底 和一个变量(锥体的高)height,一个带参数的构造方法,一个换底方法getbottom ,一个锥体体积的计算方法volume 。
④声明一个主类Exp6_1,在主方法中声明接口和锥体类的对象,输出锥体的底面积和锥体的体积(bottom*height/3)。
2、调试和运行异常处理程序。命令行参数输入“0 0”,观察自定义异常类的使用情况。源程序见附件。
注意事项:项目文件要上交到教师机相应的文件夹中。实践报告本中书写第1题源程序。
实验环境:计算机实训中心机房,win2000、eclipse 软件环境。
预习要求及思考题:复习2.7-2.8,预习3.1-3.2
附:第1题参考源程序:
package edu.ch2;
interface Calculability //声明接口 public double area ; //声明接口中的方法 class rectangle implements Calculability //声明矩形类
double w,h;
rectangle double width,double height //构造方法,初始化矩形的宽w和高h
w width;
h height; public double area //覆盖接口中的area 方法计算矩形面积
return w*h; class circle implements Calculability //声明圆形类
double r;
circle double radius //构造方法,初始化圆半径r
r radius; public double area //覆盖接口中的area 方法计算圆形面积
return 3.14159*r*r; class taper //声明锥体形类
Calculability bottom; //声明一个接口对象,以便调用底面积的计算方法area double height;
taper Calculability b,double h bottom b;
height h; void getBottom Calculability b bottom b; public double volume //声明锥体体积计算方法
return bottom.area *height /3; public class Sample2_14 public static void main String[] args taper tap; Calculability bottom; bottom new rectangle 10,20 ; //接口变量中存放对象的引用,锥体底面是矩形。
System.out.println "矩形的面积 "+bottom.area ; //bottom接口回调,求面积。
tap new taper bottom,30 ; //实例化锥体
System.out.println "矩形底的锥体的体积 "+tap.volume ;
bottom new circle 10 ; //接口变量中存放对象的引用,锥体底面是圆形。 System.out.println "圆的面积 "+bottom.area ; //bottom接口回调,求面积。
tap.getBottom bottom ; //换底
System.out.println "圆形底的锥体的体积 "+tap.volume ; 第2题参考源程序:
package edu.ch2;
class MyException extends Exception //声明自定义异常类 String ExceptionMessage "a,b同时为0!"; MyException //无参数构