创建一个名为“shape”的抽象类,该类内部含有两个抽象方法getGirth(int i)和getArea(int i),分别用来计算周长和面积;“shape”类派生出子类“triangle”,“triangle”类中按照三角形的周长和面积的计算方式对“shape”类中两个抽象方法进行覆盖,triangle构造方法具有六个参数,分别为三个顶点的横坐标和纵坐标,并在main方法中进行验证。请写出Shape、triangle类的源代码并设置用例计算输出三角形的周长和面积(注:可使用Math类)。
时间: 2024-03-10 13:50:45 浏览: 65
以下是Shape和Triangle类的源代码:
```java
// Shape.java
public abstract class Shape {
public abstract double getGirth(int i);
public abstract double getArea(int i);
}
// Triangle.java
public class Triangle extends Shape {
private double x1, y1, x2, y2, x3, y3;
public Triangle(double x1, double y1, double x2, double y2, double x3, double y3) {
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.x3 = x3;
this.y3 = y3;
}
@Override
public double getGirth(int i) {
double a = Math.sqrt(Math.pow(x1-x2, 2) + Math.pow(y1-y2, 2));
double b = Math.sqrt(Math.pow(x2-x3, 2) + Math.pow(y2-y3, 2));
double c = Math.sqrt(Math.pow(x3-x1, 2) + Math.pow(y3-y1, 2));
return a + b + c;
}
@Override
public double getArea(int i) {
double a = Math.sqrt(Math.pow(x1-x2, 2) + Math.pow(y1-y2, 2));
double b = Math.sqrt(Math.pow(x2-x3, 2) + Math.pow(y2-y3, 2));
double c = Math.sqrt(Math.pow(x3-x1, 2) + Math.pow(y3-y1, 2));
double p = (a + b + c) / 2;
return Math.sqrt(p * (p - a) * (p - b) * (p - c));
}
}
```
以下是用例代码,用于输出三角形的周长和面积:
```java
public class Main {
public static void main(String[] args) {
Triangle triangle = new Triangle(0, 0, 3, 0, 0, 4);
System.out.printf("The girth of the triangle is %.2f.\n", triangle.getGirth(0));
System.out.printf("The area of the triangle is %.2f.\n", triangle.getArea(0));
}
}
```
运行后,输出结果为:
```
The girth of the triangle is 12.00.
The area of the triangle is 6.00.
```
阅读全文