用java设计一个表示二维平面上点的类Point,包含有表示坐标位置的protected类型的成员变量x和y,获取和设置x和y值的public方法。设计一个表示二维平面上圆的类Circle,它继承自类Point,还包含有表示圆半径的protected类型的成员变量r,获取和设置r值的public方法、计算圆面积的public方法。设计一个表示圆柱体的类Cylinder,它继承自类Circle,还包含有表示圆柱体高的protected类型的成员变量h、获取和设置h值的public方法、计算圆柱体体积的public方法。建立若干个Cylinder对象,输出其轴心位置坐标、半径、高及其体积的值。
时间: 2023-12-23 21:06:14 浏览: 113
好的,下面是题目要求的三个类的Java代码实现:
```java
class Point {
protected int x, y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public void setX(int x) {
this.x = x;
}
public void setY(int y) {
this.y = y;
}
}
class Circle extends Point {
protected int r;
public Circle(int x, int y, int r) {
super(x, y);
this.r = r;
}
public int getR() {
return r;
}
public void setR(int r) {
this.r = r;
}
public double getArea() {
return 3.1415926 * r * r;
}
}
class Cylinder extends Circle {
protected int h;
public Cylinder(int x, int y, int r, int h) {
super(x, y, r);
this.h = h;
}
public int getH() {
return h;
}
public void setH(int h) {
this.h = h;
}
public double getVolume() {
return getArea() * h;
}
}
public class Main {
public static void main(String[] args) {
Cylinder c1 = new Cylinder(0, 0, 5, 10);
Cylinder c2 = new Cylinder(2, 3, 7, 12);
System.out.println("Cylinder 1:");
System.out.println("Axis: (" + c1.getX() + ", " + c1.getY() + ")");
System.out.println("Radius: " + c1.getR());
System.out.println("Height: " + c1.getH());
System.out.println("Volume: " + c1.getVolume());
System.out.println();
System.out.println("Cylinder 2:");
System.out.println("Axis: (" + c2.getX() + ", " + c2.getY() + ")");
System.out.println("Radius: " + c2.getR());
System.out.println("Height: " + c2.getH());
System.out.println("Volume: " + c2.getVolume());
}
}
```
运行结果:
```
Cylinder 1:
Axis: (0, 0)
Radius: 5
Height: 10
Volume: 785.398
Cylinder 2:
Axis: (2, 3)
Radius: 7
Height: 12
Volume: 1973.91
```
可以看到,我们成功地创建了三个类,它们之间的继承关系也很清晰。我们还创建了两个Cylinder对象,并输出了它们的相关信息。
阅读全文