继承与多态
一、实验目的:
掌握继承、多态的概念与实现方法;
掌握包和接口的定义和使用方法;
了解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 继承与多态;
abstract class Shape{
abstract public void show();
}
class Rectangle extends Shape{
protected int x;
protected int y;
protected int s;
public Rectangle(int x, int y){
this.x = x;
this.y = y;
}
public void show(){
this.s = this.x * this.y;
System.out.println(this.s);
}
}
class Square extends Shape{
protected int x;
protected int s;
public Square(int x){
this.x = x;
}
public void show(){
this.s = this.x * this.x;
System.out.println(this.s);
}
}
class Circle extends Shape{
protected double s;
protected int r;
public Circle(int x){
this.r = x;
}
public void show(){
this.s = this.r * this.r * 3.14;
System.out.println(this.s);
}
}
public class Ji {
public static void main(String[] args) {
Rectangle rect = new Rectangle(7, 8);
Square squ = new Square(9);
Circle cir = new Circle(5);
rect.show();
squ.show();
cir.show();
}
}
interface DiagArea{
double getDiagonal();
double getArea();
}
class Rect implements DiagArea{
protected int x;
protected int y;
protected double diagonal;
protected double area;
public Rect(){
}
public Rect(int x, int y){
this.x = x;
this.y = y;
}
public double getDiagonal(){
this.diagonal = Math.sqrt(this.x * this.x + this.y * this.y);
return this.diagonal;
}
public double getArea(){
this.area = this.x * this.y;
return this.area;
}
}
class Squa extends Rect{
protected int x;
public Squa(int x){
super(x, x);
this.x = x;
this.diagonal = this.getDiagonal();
this.area = this.getArea();
}
}
public class Jiekou {
public static void main(String[] args){
Squa s = new Squa(7);
System.out.println(s.diagonal);
System.out.println(s.area);
System.out.println(s.x);
}
}
浙公网安备 33010602011771号