You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

48 lines
1.1 KiB

/**
* 三角形类,继承自抽象图形类Shape
* 实现三角形的面积计算逻辑:面积 = 底 * 高 / 2
*/
public class Triangle extends Shape {
// 三角形的底和高
private double base;
private double height;
/**
* 构造方法:初始化三角形的底和高
* @param base 底(需大于0)
* @param height 高(需大于0)
*/
public Triangle(double base, double height) {
if (base <= 0 || height <= 0) {
throw new IllegalArgumentException("底和高必须大于0!");
}
this.base = base;
this.height = height;
}
/**
* 实现抽象方法:计算三角形面积
* @return 三角形的面积
*/
@Override
public double getArea() {
return (base * height) / 2;
}
// 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;
}
}