java的抽象类的三角形周长_怎么使用Java把抽象类改为接口计算三角形,长方形,圆形的面积?...
时间: 2024-03-13 19:44:40 浏览: 146
java程序代码实现矩形、三角形、圆的面积和周长计算
4星 · 用户满意度95%
抽象类的三角形周长计算代码示例:
```java
abstract class Triangle {
protected double a, b, c;
public Triangle(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
public abstract double getPerimeter();
}
class ConcreteTriangle extends Triangle {
public ConcreteTriangle(double a, double b, double c) {
super(a, b, c);
}
public double getPerimeter() {
return a + b + c;
}
}
public class Main {
public static void main(String[] args) {
Triangle t = new ConcreteTriangle(3, 4, 5);
System.out.println("Triangle perimeter: " + t.getPerimeter());
}
}
```
将抽象类改为接口,代码示例:
```java
interface Shape {
double getArea();
}
class Triangle implements Shape {
private double a, b, c;
public Triangle(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
public double getArea() {
double p = (a + b + c) / 2;
return Math.sqrt(p * (p - a) * (p - b) * (p - c));
}
}
class Rectangle implements Shape {
private double length, width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
public double getArea() {
return length * width;
}
}
class Circle implements Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getArea() {
return Math.PI * radius * radius;
}
}
public class Main {
public static void main(String[] args) {
Shape[] shapes = {new Triangle(3, 4, 5), new Rectangle(2, 3), new Circle(1)};
for (Shape s : shapes) {
System.out.println("Area: " + s.getArea());
}
}
}
```
在这个示例中,我们创建了一个 `Shape` 接口,它有一个 `getArea()` 方法。我们创建了三个具体的形状类 `Triangle`、`Rectangle` 和 `Circle`,它们都实现了 `Shape` 接口,并实现了 `getArea()` 方法。在 `Main` 类中,我们创建了一个 `Shape` 数组,并用具体的形状类的实例填充它。然后,我们循环遍历这个数组,调用每个形状的 `getArea()` 方法并打印结果。
阅读全文