4 changed files with 122 additions and 0 deletions
@ -0,0 +1,23 @@ |
|||
public class Circle extends Shape { |
|||
private double radius; |
|||
|
|||
// 构造方法
|
|||
public Circle(double radius) { |
|||
this.radius = radius; |
|||
} |
|||
|
|||
// 实现抽象方法,计算圆的面积
|
|||
@Override |
|||
public double getArea() { |
|||
return Math.PI * radius * radius; |
|||
} |
|||
|
|||
// getter和setter方法
|
|||
public double getRadius() { |
|||
return radius; |
|||
} |
|||
|
|||
public void setRadius(double radius) { |
|||
this.radius = radius; |
|||
} |
|||
} |
|||
@ -0,0 +1,33 @@ |
|||
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; |
|||
} |
|||
|
|||
// getter和setter方法
|
|||
public double getWidth() { |
|||
return width; |
|||
} |
|||
|
|||
public void setWidth(double width) { |
|||
this.width = width; |
|||
} |
|||
|
|||
public double getHeight() { |
|||
return height; |
|||
} |
|||
|
|||
public void setHeight(double height) { |
|||
this.height = height; |
|||
} |
|||
} |
|||
@ -0,0 +1,33 @@ |
|||
// 抽象类 Shape
|
|||
abstract class Shape { |
|||
// 抽象方法,计算面积
|
|||
public abstract double getArea(); |
|||
} |
|||
|
|||
// 工具类 ShapeUtil
|
|||
class ShapeUtil { |
|||
// 打印图形的面积
|
|||
public static void printArea(Shape shape) { |
|||
System.out.println("图形的面积为:" + shape.getArea()); |
|||
} |
|||
} |
|||
|
|||
// 主类 Main
|
|||
public class ShapeCalculator { |
|||
public static void main(String[] args) { |
|||
// 创建不同的图形对象
|
|||
Shape circle = new Circle(5.0); // 半径为5的圆
|
|||
Shape rectangle = new Rectangle(4.0, 6.0); // 宽4、高6的矩形
|
|||
Shape triangle = new Triangle(3.0, 8.0); // 底3、高8的三角形
|
|||
|
|||
// 使用ShapeUtil打印各图形的面积
|
|||
System.out.println("圆的面积:"); |
|||
ShapeUtil.printArea(circle); |
|||
|
|||
System.out.println("矩形的面积:"); |
|||
ShapeUtil.printArea(rectangle); |
|||
|
|||
System.out.println("三角形的面积:"); |
|||
ShapeUtil.printArea(triangle); |
|||
} |
|||
} |
|||
@ -0,0 +1,33 @@ |
|||
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; |
|||
} |
|||
|
|||
// getter和setter方法
|
|||
public double getBase() { |
|||
return base; |
|||
} |
|||
|
|||
public void setBase(double base) { |
|||
this.base = base; |
|||
} |
|||
|
|||
public double getHeight() { |
|||
return height; |
|||
} |
|||
|
|||
public void setHeight(double height) { |
|||
this.height = height; |
|||
} |
|||
} |
|||
Loading…
Reference in new issue