(Triangle类)设计一个继承了抽象类GeometricObject的新的Triangle类。绘制Triangle类和GeometricObject类的UML图并实现Trian类。编写测试程序,提示用户输入三角形的三条边,颜色以及一个表明该三角形是否填充的布尔值。程序应该使用这些边来创建一个Triangle对象,并根据用户的输入来设置color和filled属性。程序应该显示面积,周长,颜色以及表明是否被填充的真或假的值
时间: 2023-06-19 14:09:19 浏览: 81
## Triangle类和GeometricObject类的UML图
```
GeometricObject
-color: String
-filled: boolean
+GeometricObject()
+GeometricObject(color: String, filled: boolean)
+getColor(): String
+setColor(color: String): void
+isFilled(): boolean
+setFilled(filled: boolean): void
+toString(): String
|
|
|
V
Triangle
-side1: double
-side2: double
-side3: double
+Triangle()
+Triangle(side1: double, side2: double, side3: double)
+Triangle(side1: double, side2: double, side3: double, color: String, filled: boolean)
+getSide1(): double
+getSide2(): double
+getSide3(): double
+getArea(): double
+getPerimeter(): double
+toString(): String
```
## 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 Triangle(double side1, double side2, double side3, String color, boolean filled) {
super(color, filled);
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 = (this.side1 + this.side2 + this.side3) / 2.0;
return Math.sqrt(s * (s - this.side1) * (s - this.side2) * (s - this.side3));
}
public double getPerimeter() {
return this.side1 + this.side2 + this.side3;
}
public String toString() {
return "Triangle: side1 = " + this.side1 + " side2 = " + this.side2 +
" side3 = " + this.side3;
}
}
```
## 测试程序
```java
import java.util.Scanner;
public class TestTriangle {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter three sides of a triangle: ");
double side1 = input.nextDouble();
double side2 = input.nextDouble();
double side3 = input.nextDouble();
System.out.print("Enter the color of the triangle: ");
String color = input.next();
System.out.print("Is the triangle filled (true / false)? ");
boolean filled = input.nextBoolean();
Triangle t1 = new Triangle(side1, side2, side3, color, filled);
System.out.println("Triangle t1: " + t1.toString());
System.out.println("Area: " + t1.getArea());
System.out.println("Perimeter: " + t1.getPerimeter());
System.out.println("Color: " + t1.getColor());
System.out.println("Is Filled: " + t1.isFilled());
}
}
```
阅读全文