《Java语言程序设计》实验报告
实验名称 姓名 专业 学号 班级 实验四 类的继承性与多态性 成绩 日期 (1)掌握类的继承原则。 实验 目的 (2)正确使用方法的重载和覆盖等多态概念设计可复用方法。 (3)掌握声明抽象类的方法,理解抽象类的作用。 实验 本次共有 2 个练习,完成 2 个。 进度 (1)设计一个抽象类Graphics(图形类),包含私有成员变量shape(形状)、带参数的构造方法(确定该图形是什么形状)、用于计算面积的抽象方法area( )、用于显示面积的成员方法print( )。 代码: package exp4; 实 验 内 容 public abstract class Graphics { } private String shape; protected Graphics(String shape) { } public abstract double area(); public void print() { } System.out.print(\该\+this.shape+\的面积为:\+this.area()+\); this.shape = shape; (2)设计两个Graphics类的子类:Rectangle类(矩形)和Circle类(圆),编译并运行使程序运行
结果如下所示:
矩形的面积为: 100.0
圆的面积为: 314.1592653589793
代码:
package exp4;//矩形类
public class Rectangle extends Graphics{
protected double a; protected double b;
public Rectangle(double a,double b) {
super(\矩形\); this.a=a; this.b=b;
}
public double area() { }
return this.a*this.b; }
实 验 内 容
package exp4;//圆形类
public class Circle extends Graphics {
package exp4;//调用上述类
public class Graphics_ex {
public static void main(String args[]) {
Graphics g = new Rectangle(4,25); protected double r; public Circle(double r) {
super(\圆形\); this.r=r;
}
public double area() { }
return Math.PI*this.r*this.r; }
} }
g.print();
g = new Circle(10); g.print();
运行结果:
本次试验运行情况良好。通过本次试验我掌握类的继承原则、重载和覆盖等多态概念设计的正确使用方法、声明抽象类的方法,还理解了抽象类的作用。
实验 分析