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