利用继承的思想,创建图形、正方形、圆形、三角形这些类,编写上转型程序并计算正方形、圆形和三角形的面积和周长。
时间: 2024-06-13 11:03:47 浏览: 168
java程序代码实现矩形、三角形、圆的面积和周长计算
4星 · 用户满意度95%
首先,我们可以创建一个抽象类Shape,作为其他图形类的父类,其中包含计算面积和周长的抽象方法。然后,我们可以创建Square、Circle和Triangle类,分别继承Shape类,并实现计算面积和周长的方法。
下面是示例代码:
```
abstract class Shape {
public abstract double getArea();
public abstract double getPerimeter();
}
class Square extends Shape {
private double side;
public Square(double side) {
this.side = side;
}
public double getArea() {
return side * side;
}
public double getPerimeter() {
return 4 * side;
}
}
class Circle extends Shape {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getArea() {
return Math.PI * radius * radius;
}
public double getPerimeter() {
return 2 * Math.PI * radius;
}
}
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;
}
public double getArea() {
double p = (a + b + c) / 2;
return Math.sqrt(p * (p - a) * (p - b) * (p - c)); }
public double getPerimeter() {
return a + b + c;
}
}
```
接下来,我们可以编写一个测试程序,创建Square、Circle和Triangle对象,并计算它们的面积和周长。同时,我们可以使用向上转型的方式,将它们转换为Shape类型,以便于统一计算。
```
public class Test {
public static void main(String[] args) {
Shape[] shapes = new Shape[3];
shapes[0] = new Square(2);
shapes[1] = new Circle(3);
shapes[2] = new Triangle(3, 4, 5);
for (Shape shape : shapes) {
System.out.println("Area: " + shape.getArea());
System.out.println("Perimeter: " + shape.getPerimeter());
}
}
}
```
输出结果如下:
```
Area: 4.0
Perimeter: 8.0
Area: 28.274333882308138
Perimeter: 18.84955592153876
Area: 6.0
Perimeter: 12.0
```
阅读全文