4.编程题 (1)设计一个名为Geometric的几何图形的抽象类,该类包括: 1设计一个名为Triangle的三角形类来实现CGcometric类,该类包括。 0三个名为sidel.side2和side的double属性表示三角形的三条边。 2一个无参构造方法创建三角形。 一个能创建指定sidel、side2和side3的矩形的构造方法。 1 sidel、side2和side3的访问器方法。 6一个名为getArea()的方法,返回该三角形的面积。 ⑥一个名为getPerimeter()的方法,返回该三角形的周长。 2一个名为isTriangle()的方法,判断三边是否能构成三角形。 8一个名为toString()的方法,返回三边较小的字符串描述。(5)编写测试类,测试图形的面积和周长。
时间: 2024-03-19 20:45:15 浏览: 166
下面是对应的Java代码:
Geometric.java
```java
public abstract class Geometric {
protected String color;
protected boolean filled;
public Geometric() {}
public Geometric(String color, boolean filled) {
this.color = color;
this.filled = filled;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public boolean isFilled() {
return filled;
}
public void setFilled(boolean filled) {
this.filled = filled;
}
public abstract double getArea();
public abstract double getPerimeter();
public String toString() {
return "Geometric[color=" + color + ", filled=" + filled + "]";
}
}
```
Triangle.java
```java
public class Triangle extends Geometric {
private double side1;
private double side2;
private double side3;
public Triangle() {}
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 void setSide1(double side1) {
this.side1 = side1;
}
public double getSide2() {
return side2;
}
public void setSide2(double side2) {
this.side2 = side2;
}
public double getSide3() {
return side3;
}
public void setSide3(double side3) {
this.side3 = side3;
}
public boolean isTriangle() {
return side1 + side2 > side3 && side1 + side3 > side2 && side2 + side3 > side1;
}
public double getArea() {
double p = (side1 + side2 + side3) / 2;
return Math.sqrt(p * (p - side1) * (p - side2) * (p - side3));
}
public double getPerimeter() {
return side1 + side2 + side3;
}
public String toString() {
double[] sides = {side1, side2, side3};
Arrays.sort(sides);
return "Triangle[" + super.toString() + ", side1=" + sides[0] + ", side2=" + sides[1] + ", side3=" + sides[2] + "]";
}
}
```
Test.java
```java
public class Test {
public static void main(String[] args) {
Geometric g1 = new Circle(5, "red", true);
System.out.println(g1);
System.out.println("Area: " + g1.getArea());
System.out.println("Perimeter: " + g1.getPerimeter());
Geometric g2 = new Rectangle(3, 4, "blue", false);
System.out.println(g2);
System.out.println("Area: " + g2.getArea());
System.out.println("Perimeter: " + g2.getPerimeter());
Geometric g3 = new Triangle(3, 4, 5, "green", true);
System.out.println(g3);
System.out.println("Area: " + g3.getArea());
System.out.println("Perimeter: " + g3.getPerimeter());
System.out.println("Is triangle: " + ((Triangle) g3).isTriangle()));
}
}
```
注意:此处的测试代码只是示例,具体的测试代码根据实际情况进行编写。
阅读全文