练习2:利用面向对象的编程方法,设计圆类Circle,包含属性(半径)和 计算圆面积的方法。定义测试类,创建该Circle类的对象,并进行测试。java来写
时间: 2024-10-15 09:13:43 浏览: 41
在Java中,我们可以设计一个简单的`Circle`类来表示圆,它有一个属性`radius`代表圆的半径,然后我们定义一个名为`getArea()`的方法来计算圆的面积。这是一个基础的面向对象设计:
```java
public class Circle {
private double radius; // 圆的半径
// 构造函数
public Circle(double radius) {
this.radius = radius;
}
// 计算圆面积的方法
public double getArea() {
return Math.PI * radius * radius; // 使用Math.PI乘以半径的平方
}
}
// 测试类TestCircle
public class TestCircle {
public static void main(String[] args) {
// 创建Circle对象
Circle circle = new Circle(5.0);
// 调用getArea方法并打印结果
double area = circle.getArea();
System.out.println("The area of the circle with radius " + circle.radius + " is " + area);
// 另一个示例,展示多态性
Circle anotherCircle = new Circle(10.0);
System.out.println("The area of another circle with radius " + anotherCircle.radius + " is " + anotherCircle.getArea());
}
}
```
在这个例子中,`TestCircle`类用于测试`Circle`类的功能。通过实例化不同的`Circle`对象并调用`getArea()`方法,你可以验证计算是否正确。
阅读全文
相关推荐
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.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)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)