Compare commits

...

3 Commits

  1. 12
      w4/Circle.java
  2. 13
      w4/Main.java
  3. 14
      w4/Rectangle.java
  4. 4
      w4/Shape.java
  5. 6
      w4/ShapeUtil.java
  6. 14
      w4/Triangle.java

12
w4/Circle.java

@ -0,0 +1,12 @@
public class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
@Override
public double getArea() {
return Math.PI * radius * radius;
}
}

13
w4/Main.java

@ -0,0 +1,13 @@
public class Main {
public static void main(String[] args) {
// 创建不同图形
Shape circle = new Circle(5);
Shape rectangle = new Rectangle(4, 6);
Shape triangle = new Triangle(3, 4);
// 统一打印面积
ShapeUtil.printArea(circle);
ShapeUtil.printArea(rectangle);
ShapeUtil.printArea(triangle);
}
}

14
w4/Rectangle.java

@ -0,0 +1,14 @@
public 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;
}
}

4
w4/Shape.java

@ -0,0 +1,4 @@
public abstract class Shape {
// 计算面积的抽象方法
public abstract double getArea();
}

6
w4/ShapeUtil.java

@ -0,0 +1,6 @@
public class ShapeUtil {
// 统一打印任意图形的面积
public static void printArea(Shape shape) {
System.out.println("图形面积 = " + shape.getArea());
}
}

14
w4/Triangle.java

@ -0,0 +1,14 @@
public 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;
}
}
Loading…
Cancel
Save