设计一个circle类 包括半径和颜色属性 编写构造方法和其他方法 计算圆的周长和面积 请编写程序验证类的功能
时间: 2024-12-24 21:28:35 浏览: 3
设计一个Circle类,我们可以按照以下步骤进行:
```java
public class Circle {
// 属性
private double radius;
private String color;
// 构造方法
public Circle(double radius, String color) {
this.radius = radius;
this.color = color;
}
// 计算圆的周长
public double calculateCircumference() {
return Math.PI * 2 * radius;
}
// 计算圆的面积
public double calculateArea() {
return Math.PI * Math.pow(radius, 2);
}
// 定义方法显示Circle的信息
@Override
public String toString() {
return "Circle [radius=" + radius + ", color=" + color + "]";
}
}
// 验证类功能的主函数
public class Main {
public static void main(String[] args) {
// 创建一个Circle实例
Circle circle = new Circle(5.0, "Red");
// 调用计算周长和面积的方法
double circumference = circle.calculateCircumference();
double area = circle.calculateArea();
// 打印信息
System.out.println("Circle with radius " + circle.radius + " and color " + circle.color + ":");
System.out.println("Circumference: " + circumference);
System.out.println("Area: " + area);
// 输出Circle对象的字符串形式
System.out.println(circle);
}
}
```
在这个例子中,我们创建了一个Circle类,包含半径和颜色属性,以及计算周长和面积的方法。`main`函数用于测试Circle类的实例,并打印出相关信息。你可以通过运行这个`Main`类来验证Circle类是否能正常工作。
阅读全文
相关推荐
![text/x-java](https://img-home.csdnimg.cn/images/20210720083646.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)