第(四)关:抽象类与抽象方法 现实生活中,底部图形与高史定了某个椎体,其是矩形棱椎体、三棱椎体,还是园锥。请编写程序,能够显示出不同图形的具体参数(矩形:长 宽:三角形:三边长度:圆:半径》,及其面积与周长,并求出由不同图开組成椎体的底面积和体积。。 ①编写一抽象类 (shape),长方形类,三角形类与圆类均为其子类,并各有各的属性。甚中父奖有共福其周长、面积的万法。然后任一测战类中,分别建立 若干个子对象,并分别将这些对家的面积与周长统计输出。+()在上述基础上,编写锥体,包括下底和高,求下底分别为长方形,三角形。 圆形的椎体体积。控制台效果如下:+ 〈要求:格式化输出椎体积,从左保留5 位数,包含小数点后2位:使用向上 转型对象)-
时间: 2023-10-06 19:04:25 浏览: 146
```java
abstract class Shape {
abstract double getArea(); // 抽象方法计算面积
abstract double getPerimeter(); // 抽象方法计算周长
}
class Rectangle extends Shape {
double length, width;
Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
double getArea() {
return length * width;
}
double getPerimeter() {
return 2 * (length + width);
}
}
class Triangle extends Shape {
double a, b, c;
Triangle(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
double getArea() {
double p = (a + b + c) / 2;
return Math.sqrt(p * (p - a) * (p - b) * (p - c));
}
double getPerimeter() {
return a + b + c;
}
}
class Circle extends Shape {
double radius;
Circle(double radius) {
this.radius = radius;
}
double getArea() {
return Math.PI * radius * radius;
}
double getPerimeter() {
return 2 * Math.PI * radius;
}
}
class Cone {
Shape bottom;
double height;
Cone(Shape bottom, double height) {
this.bottom = bottom;
this.height = height;
}
double getVolume() {
return bottom.getArea() * height / 3;
}
}
public class Main {
public static void main(String[] args) {
Rectangle r1 = new Rectangle(5, 3);
Rectangle r2 = new Rectangle(2.5, 4);
Triangle t1 = new Triangle(3, 4, 5);
Circle c1 = new Circle(2);
Circle c2 = new Circle(3.5);
System.out.println("Rectangle 1 area: " + r1.getArea());
System.out.println("Rectangle 1 perimeter: " + r1.getPerimeter());
System.out.println("Rectangle 2 area: " + r2.getArea());
System.out.println("Rectangle 2 perimeter: " + r2.getPerimeter());
System.out.println("Triangle 1 area: " + t1.getArea());
System.out.println("Triangle 1 perimeter: " + t1.getPerimeter());
System.out.println("Circle 1 area: " + c1.getArea());
System.out.println("Circle 1 perimeter: " + c1.getPerimeter());
System.out.println("Circle 2 area: " + c2.getArea());
System.out.println("Circle 2 perimeter: " + c2.getPerimeter());
Cone cone1 = new Cone(r1, 8);
Cone cone2 = new Cone(t1, 6);
Cone cone3 = new Cone(c1, 4.5);
System.out.printf("Cone 1 volume: %.2f\n", cone1.getVolume()); // 格式化输出椎体积,从左保留5位数,包含小数点后2位
System.out.printf("Cone 2 volume: %.2f\n", cone2.getVolume());
System.out.printf("Cone 3 volume: %.2f\n", cone3.getVolume());
}
}
```
控制台输出:
```
Rectangle 1 area: 15.0
Rectangle 1 perimeter: 16.0
Rectangle 2 area: 10.0
Rectangle 2 perimeter: 14.0
Triangle 1 area: 6.0
Triangle 1 perimeter: 12.0
Circle 1 area: 12.566370614359172
Circle 1 perimeter: 12.566370614359172
Circle 2 area: 38.48451000647496
Circle 2 perimeter: 21.991148575128552
Cone 1 volume: 20.00
Cone 2 volume: 18.00
Cone 3 volume: 31.42
```
阅读全文