9. 创建一个名为“shape”的抽象类,该类内部含有两个抽象方法getGirth(int i)和getArea(int i),分别用来计算周长和面积;“shape”类派生出子类“triangle”,“triangle”类中按照三角形的周长和面积的计算方式对“shape”类中两个抽象方法进行覆盖,triangle构造方法具有六个参数,分别为三个顶点的横坐标和纵坐标,并在main方法中进行验证。请写出Shape、triangle类的源代码并设置用例计算输出三角形的周长和面积(注:可使用Math类)。Java程序
时间: 2024-03-01 07:50:44 浏览: 68
Shape.java文件:
```java
public abstract class Shape {
public abstract double getGirth(int i);
public abstract double getArea(int i);
}
```
Triangle.java文件:
```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((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
double b = Math.sqrt((x3 - x2) * (x3 - x2) + (y3 - y2) * (y3 - y2));
double c = Math.sqrt((x3 - x1) * (x3 - x1) + (y3 - y1) * (y3 - y1));
return a + b + c;
}
@Override
public double getArea(int i) {
double a = Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
double b = Math.sqrt((x3 - x2) * (x3 - x2) + (y3 - y2) * (y3 - y2));
double c = Math.sqrt((x3 - x1) * (x3 - x1) + (y3 - y1) * (y3 - y1));
double p = (a + b + c) / 2;
return Math.sqrt(p * (p - a) * (p - b) * (p - c));
}
}
```
Main.java文件:
```java
public class Main {
public static void main(String[] args) {
Triangle triangle = new Triangle(0, 0, 3, 0, 0, 4);
System.out.println("三角形的周长为:" + triangle.getGirth(0));
System.out.println("三角形的面积为:" + triangle.getArea(0));
}
}
```
输出结果为:
```
三角形的周长为:12.0
三角形的面积为:6.0
```
阅读全文