Browse Source

添加 'w4/ShapeAreaCalculator.java'

main
dengxitong 3 weeks ago
parent
commit
297d657628
  1. 72
      w4/ShapeAreaCalculator.java

72
w4/ShapeAreaCalculator.java

@ -0,0 +1,72 @@
package src.main.w5;
abstract class Shape {
public abstract double getArea();
}
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
}
class Rectangle extends Shape {
private double width;
private double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
@Override
public double getArea() {
return width * height;
}
}
class Triangle extends Shape {
private double base;
private double height;
public Triangle(double base, double height) {
this.base = base;
this.height = height;
}
@Override
public double getArea() {
return 0.5 * base * height;
}
}
class ShapeUtil {
public static void printArea(Shape shape) {
System.out.printf("该图形的面积为:%.2f%n", shape.getArea());
}
}
public class ShapeAreaCalculator {
public static void main(String[] args) {
Shape circle = new Circle(2.0);
Shape rectangle = new Rectangle(3.0, 4.0);
Shape triangle = new Triangle(3.0, 4.0);
System.out.println("圆形:");
ShapeUtil.printArea(circle);
System.out.println("矩形:");
ShapeUtil.printArea(rectangle);
System.out.println("三角形:");
ShapeUtil.printArea(triangle);
}
}
Loading…
Cancel
Save