Java 面积计算:抽象类 Shape 及其子类实现
以下是以 Java 语言实现该设定的代码:
abstract class Shape {
public abstract double getArea();
}
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getArea() {
return Math.PI * radius * radius;
}
}
class Rectangle extends Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
public double getArea() {
return length * width;
}
}
class Triangle extends Shape {
private double base;
private double height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
public double getArea() {
return 0.5 * base * height;
}
}
class TestShape {
static double area = 0;
public static void countArea(Shape s) {
area += s.getArea();
}
public static void main(String[] args) {
Circle s1 = new Circle(5);
Rectangle s2 = new Rectangle(4, 6);
Triangle s3 = new Triangle(3, 8);
countArea(s1);
countArea(s2);
countArea(s3);
System.out.println('Total area: ' + area);
}
}
运行以上代码,将输出三个形状的面积之和。
原文地址: https://www.cveoy.top/t/topic/E1f 著作权归作者所有。请勿转载和采集!