类和对象课内实践课 java练习题 按要求编写程序,完成以下功能?

2024-11-22 23:07:48
推荐回答(1个)
回答(1):

package com.ZL;

public abstract class Shape {
public abstract double getArea(Shape a);
}

package com.ZL;

public class Circle extends Shape{
private double radius;

public Circle(double radius) {
super();
this.radius = radius;
}

@Override
public double getArea(Shape a) {
Circle c = (Circle)a;
double r = c.radius;
return (Math.PI)*(Math.pow(r, 2));
}

}

package com.ZL;

public class Rectangle extends Shape{
private double length;
private double width;

public Rectangle(double length, double width) {
super();
this.length = length;
this.width = width;
}

@Override
public double getArea(Shape a) {
Rectangle r = (Rectangle)a;
return r.length * r.width;
}

}

package com.ZL;

public class Triangle extends Shape{
private double length;
private double heigth;

public Triangle(double length, double heigth) {
super();
this.length = length;
this.heigth = heigth;
}

@Override
public double getArea(Shape a) {
Triangle t = (Triangle)a;
return (t.length * t.heigth) / 2;
}

}

package com.ZL;

public class Trapezoid extends Shape{
private double upperLength;
private double bottonLength;
private double heigth;

public Trapezoid(double upperLength, double bottonLength, double heigth) {
super();
this.upperLength = upperLength;
this.bottonLength = bottonLength;
this.heigth = heigth;
}

@Override
public double getArea(Shape a) {
Trapezoid t = (Trapezoid)a;
return (t.upperLength + t.bottonLength) / 2 * t.heigth;
}

}

package com.ZL;

public class TestShape {
public static void main(String[] args) {
Shape circle = new Circle(5.3);
Shape rectangle = new Rectangle(3.0,6.6);
Shape triangle = new Triangle(8.0,5.0);
Shape trapezoid = new Trapezoid(4.0,7.2,12.0);

System.out.println(circle.getArea(circle));
System.out.println(rectangle.getArea(rectangle));
System.out.println(triangle.getArea(triangle));
System.out.println(trapezoid.getArea(trapezoid));
}
}

输出结果
88.24733763933729
19.799999999999997
20.0
67.19999999999999

这要是不采纳就说不过去了哈🧐