继承
实验五 继承与多态
一、实验目的:
掌握继承、多态的概念与实现方法;
掌握包和接口的定义和使用方法;
了解JAVA语言实现多继承的途径;
二、实验内容:
1.定义抽象类Shape,抽象方法为showArea(),求出面积并显示,定义矩形类Rectangle,正方形类Square,圆类 Circle,根据各自的属性,用showArea方法求出各自的面积,在main方法中构造3个对象,调用showArea方法。
定义接口DiagArea,其中包含方法double getDiagonal()求对角线长, double getArea()求面积,定义一个矩形类,实现此接口,并自行扩充成员变量和方法,定义一个正方形类继承矩形类(如矩形有长w和宽h,正方形有边x,并有相应的构造函数,有一个方法中一次直接显示边长、面积和对角线长),在另一类中的主方法里使用测试该类。
三、实验要求:
1. 能实现类的继承关系;
2. 用多种方法创建各个类的对象;
3. 程序应包括各个调用方法的执行结果的显示。
4. 写出实验报告。要求记录编译和执行Java程序当中的系统错误信息提示,并给出解决办法。
四、实验步骤:
1.(第1题)定义抽象类Shape,抽象方法为showArea(),再定义矩形类Rectangle,正方形类Square,圆类 Circle,和各自的属性。定义主类、主方法,在main方法中构造3个对象,调用showArea方法;定义接口DiagArea,其中包含方法double getDiagonal(),在主main方法中输出方法执行结果。
package eww; abstract class Shape { abstract public void showArea(); } class Rectangle extends Shape { protected int weight; protected int height; protected int s; public void showArea (){ this.s = this.weight * this.height; System.out.println(this.s); } public Rectangle(int weight, int height){ this.weight = weight; this.height = height; } } class Square extends Shape { protected int weight; protected int s; public void showArea (){ this.s = this.weight * this.weight; System.out.println(this.s); } public Square(int weight){ this.weight = weight; } } class Circle extends Shape { protected int r; protected int s; public void showArea (){ this.s = (int) (this.r * 3.14); System.out.println(this.s); } public Circle(int r){ this.r = r; } } interface DiagArea{ public double getDiagonal(); } public class Jicheng implements DiagArea{ public double getDiagonal(){ return 0.2; } public static void main(String[] args){ Rectangle juxing = new Rectangle(5, 7); Square zhengfang = new Square(8); Circle yuan = new Circle(9); juxing.showArea(); zhengfang.showArea(); yuan.showArea(); } }优质内容筛选与推荐>>