用JAVA语言写一个完整的程序完成下面内容,并写好注释: 在几何上,有一种立体图形叫直棱柱(right prism),直棱柱的上下底面可以是圆形,三角形,四边形,五边形等等。 请创建一个抽象类RightPrism(构造方法为Shape类和double型高),以及抽象方法(体积公式calcVolume,侧面积公式calcLateralArea ),并用面向对象的思想,实现圆柱体、三棱柱、正方体、长方体。要求以 RightPrism xxx = new CircularCylinder ()这种多态的方式调用。
时间: 2023-06-03 18:05:12 浏览: 244
Java编程语言的第一个程序.docx
抽象类 RightPrism 的示例代码如下:
```
abstract class RightPrism extends Shape {
double height;
public RightPrism(double height) {
this.height = height;
}
public abstract double calcVolume();
public abstract double calcLateralArea();
}
```
圆柱体(CircularCylinder)的示例代码如下:
```
class CircularCylinder extends RightPrism {
double radius;
public CircularCylinder(double radius, double height) {
super(height);
this.radius = radius;
}
public double calcVolume() {
return Math.PI * radius * radius * height;
}
public double calcLateralArea() {
return 2 * Math.PI * radius * height;
}
}
```
三棱柱(TriangularPrism)的示例代码如下:
```
class TriangularPrism extends RightPrism {
double base;
double side;
public TriangularPrism(double base, double side, double height) {
super(height);
this.base = base;
this.side = side;
}
public double calcVolume() {
return 0.5 * base * side * height;
}
public double calcLateralArea() {
return base * height + side * Math.sqrt(height * height + base * base / 4);
}
}
```
正方体(Cube)的示例代码如下:
```
class Cube extends RightPrism {
double side;
public Cube(double side) {
super(side);
this.side = side;
}
public double calcVolume() {
return side * side * side;
}
public double calcLateralArea() {
return 4 * side * side;
}
}
```
长方体(RectangularPrism)的示例代码如下:
```
class RectangularPrism extends RightPrism {
double length;
double width;
public RectangularPrism(double length, double width, double height) {
super(height);
this.length = length;
this.width = width;
}
public double calcVolume() {
return length * width * height;
}
public double calcLateralArea() {
return 2 * height * (length + width);
}
}
```
要以多态的方式调用,可以使用以下代码:
```
RightPrism prism1 = new CircularCylinder(2.0, 5.0);
RightPrism prism2 = new TriangularPrism(3.0, 4.0, 6.0);
RightPrism prism3 = new Cube(4.0);
RightPrism prism4 = new RectangularPrism(3.0, 4.0, 5.0);
System.out.println(prism1.calcVolume()); // Output: 62.83185307179586
System.out.println(prism2.calcLateralArea()); // Output: 59.71454272590896
System.out.println(prism3.calcVolume()); // Output: 64.0
System.out.println(prism4.calcLateralArea()); // Output: 46.0
```
注释详见代码。
阅读全文