(1)设计一个表示圆的类Circle,其中有半径属性、构造方法和计算圆面积 的方法; (2)设计一个表示圆柱体的类Cylinder,它继承自圆类Circle,它包含有表示圆柱体高的protected类型的成员变量h,获取和设置h值的public方法、计算圆柱体体积的public方法; 3)要求父类和子类位于不同的包中; 4)编写一个用于测试的主类,对Cylinder类进行测试。
时间: 2024-02-19 11:58:15 浏览: 84
好的,下面是代码实现:
首先,Circle类:
```
package com.example.shape;
public class Circle {
protected double radius;
public Circle(double radius) {
this.radius = radius;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public double getArea() {
return Math.PI * radius * radius;
}
}
```
然后,Cylinder类:
```
package com.example.shape;
public class Cylinder extends Circle {
protected double height;
public Cylinder(double radius, double height) {
super(radius);
this.height = height;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getVolume() {
return super.getArea() * height;
}
}
```
注意到,Cylinder类中调用了父类Circle的getArea方法。
最后,测试类Main:
```
package com.example.test;
import com.example.shape.Cylinder;
public class Main {
public static void main(String[] args) {
Cylinder cylinder = new Cylinder(2.0, 5.0);
System.out.println("Cylinder radius: " + cylinder.getRadius());
System.out.println("Cylinder height: " + cylinder.getHeight());
System.out.println("Cylinder volume: " + cylinder.getVolume());
}
}
```
运行结果:
```
Cylinder radius: 2.0
Cylinder height: 5.0
Cylinder volume: 62.83185307179586
```
注意到,Circle和Cylinder类位于不同的包中,需要使用import语句引入。
阅读全文
相关推荐
![text/x-java](https://img-home.csdnimg.cn/images/20250102104920.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)