java设计一个Triangle类,继承自GeometricObject类,该类包括三角形三边(默认值1.0),返回面积,周长,及三角形的字符串描述。并且画出程序的类图
时间: 2024-05-10 17:19:44 浏览: 109
java用接口、多态、继承、类计算三角形和矩形周长及面积的方法
5星 · 资源好评率100%
下面是Java中Triangle类的代码实现以及类图:
```java
public class Triangle extends GeometricObject {
private double side1;
private double side2;
private double side3;
public Triangle() {
this.side1 = 1.0;
this.side2 = 1.0;
this.side3 = 1.0;
}
public Triangle(double side1, double side2, double side3) {
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
public double getSide1() {
return side1;
}
public double getSide2() {
return side2;
}
public double getSide3() {
return side3;
}
public double getArea() {
double s = (side1 + side2 + side3) / 2;
return Math.sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
public double getPerimeter() {
return side1 + side2 + side3;
}
public String toString() {
return "Triangle: side1 = " + side1 + " side2 = " + side2 + " side3 = " + side3;
}
}
```
下面是类图:
```
+-----------------+
| GeometricObject |
+-----------------+
| -color: String |
| -filled: boolean|
| +GeometricObject()|
| +GeometricObject(color: String, filled: boolean)|
| +getColor(): String|
| +setColor(color: String): void|
| +isFilled(): boolean|
| +setFilled(filled: boolean): void|
| +getArea(): double|
| +getPerimeter(): double|
| +toString(): String|
+-----------------+
^
|
+---------------+
| Triangle |
+---------------+
| -side1: double|
| -side2: double|
| -side3: double|
+---------------+
| +Triangle()|
| +Triangle(side1: double, side2: double, side3: double)|
| +getSide1(): double|
| +getSide2(): double|
| +getSide3(): double|
| +getArea(): double|
| +getPerimeter(): double|
| +toString(): String|
+---------------+
```
阅读全文