编写一个Java源程序,该源文件中有3个类:Circle类、Cylinder类和Test2类,分别用来刻画“圆形”、“圆柱体”和测试用类,具体要求如下: a) Circle类具有类型为double的半径(r)属性,具有返回周长(getPerimeter)、面积(getArea)的功能,其中求周长和求面积方法分别使用实例方法和类方法两种方式实现。自行补充类的get/set方法、有参/无参构造方法、toString方法。 b) 以组合方式定义圆柱体Cylinder类,具有高(h)、底面(undersurface)属性,底面是圆类型,具有返回表面积(getSurfaceArea)和体积(getVolumn)方法。自行补充类的get/set方法、有参/无参构造方法、toString方法。 c) 编写测试类Test2,分别调用类方法和实例方法,计算输出半径为5和8的圆面积和周长;以以上两个圆为底面,计算高均为8的圆柱体的表面积和体积。
时间: 2023-05-25 19:06:57 浏览: 95
定义三个类Point,Circle和Cylinder,Point类为基类,为上述3个类添加计算面积的成员函数Area(),要求函数Area()采用虚函数的形式,并通过基类指针调用虚函数Area()。
Circle类代码如下:
```
public class Circle {
private double r;
public Circle() {
}
public Circle(double r) {
this.r = r;
}
public double getR() {
return r;
}
public void setR(double r) {
this.r = r;
}
public double getPerimeter() {
return 2 * Math.PI * r;
}
public double getArea() {
return Math.PI * r * r;
}
public static double getPerimeter(double r) {
return 2 * Math.PI * r;
}
public static double getArea(double r) {
return Math.PI * r * r;
}
@Override
public String toString() {
return "Circle{" +
"r=" + r +
'}';
}
}
```
Cylinder类代码如下:
```
public class Cylinder {
private double h;
private Circle undersurface;
public Cylinder() {
}
public Cylinder(double h, Circle undersurface) {
this.h = h;
this.undersurface = undersurface;
}
public double getH() {
return h;
}
public void setH(double h) {
this.h = h;
}
public Circle getUndersurface() {
return undersurface;
}
public void setUndersurface(Circle undersurface) {
this.undersurface = undersurface;
}
public double getSurfaceArea() {
double circleArea = undersurface.getArea();
double circlePerimeter = undersurface.getPerimeter();
return 2 * circleArea + circlePerimeter * h;
}
public double getVolume() {
double circleArea = undersurface.getArea();
return circleArea * h;
}
@Override
public String toString() {
return "Cylinder{" +
"h=" + h +
", undersurface=" + undersurface +
'}';
}
}
```
Test2类代码如下:
```
public class Test2 {
public static void main(String[] args) {
Circle circle1 = new Circle(5);
System.out.println("圆1的面积是:" + circle1.getArea());
System.out.println("圆1的周长是:" + circle1.getPerimeter());
Circle circle2 = new Circle(8);
System.out.println("圆2的面积是:" + Circle.getArea(circle2.getR()));
System.out.println("圆2的周长是:" + Circle.getPerimeter(circle2.getR()));
Cylinder cylinder = new Cylinder(8, circle1);
System.out.println("圆柱体的表面积是:" + cylinder.getSurfaceArea());
System.out.println("圆柱体的体积是:" + cylinder.getVolume());
cylinder.setUndersurface(circle2);
System.out.println("圆柱体的表面积是:" + cylinder.getSurfaceArea());
System.out.println("圆柱体的体积是:" + cylinder.getVolume());
}
}
```
阅读全文