用java 定义一个抽象类,它包含两个抽象方法面积和周长,从Shape 类派生出三角类,用面积方法来计算面积,用周长来计算周长。然后通过函数设定三角形三边长度为4,5,3,求三角形的面积与周长并输出,且输出三角形的三边长。(输出保留小数点后有效二位)
时间: 2024-05-01 18:19:18 浏览: 83
计算三角形的面积和周长(java)
5星 · 资源好评率100%
以下是Java代码实现:
```java
abstract class Shape {
public abstract double getArea();
public abstract double getPerimeter();
}
class Triangle extends Shape {
private double a;
private double b;
private double c;
public Triangle(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
@Override
public double getArea() {
double p = getPerimeter() / 2;
return Math.sqrt(p * (p - a) * (p - b) * (p - c));
}
@Override
public double getPerimeter() {
return a + b + c;
}
public double getA() {
return a;
}
public double getB() {
return b;
}
public double getC() {
return c;
}
}
public class Main {
public static void main(String[] args) {
Triangle triangle = new Triangle(4, 5, 3);
System.out.println("Triangle sides: " + triangle.getA() + " " + triangle.getB() + " " + triangle.getC());
System.out.printf("Triangle area: %.2f\n", triangle.getArea());
System.out.printf("Triangle perimeter: %.2f\n", triangle.getPerimeter());
}
}
```
运行结果:
```
Triangle sides: 4.0 5.0 3.0
Triangle area: 6.00
Triangle perimeter: 12.00
```
阅读全文