使用抽象类及抽象方法用Java编写代码求圆的体积及表面积同时使用format方法规范化结果
时间: 2024-05-16 14:12:57 浏览: 9
以下是使用抽象类及抽象方法用Java编写代码求圆的体积及表面积同时使用format方法规范化结果的示例代码:
```
import java.text.DecimalFormat;
// 抽象类
abstract class Circle {
protected double radius;
public Circle(double radius) {
this.radius = radius;
}
// 抽象方法,求圆的面积
public abstract double getArea();
// 抽象方法,求圆的体积
public abstract double getVolume();
}
// 圆的实现类
class Round extends Circle {
public Round(double radius) {
super(radius);
}
// 实现求圆的面积
public double getArea() {
return Math.PI * radius * radius;
}
// 实现求圆的体积
public double getVolume() {
return 4.0 / 3.0 * Math.PI * radius * radius * radius;
}
}
public class Main {
public static void main(String[] args) {
Circle c = new Round(5.0);
DecimalFormat df = new DecimalFormat("#.##");
// 求圆的面积并格式化输出
double area = c.getArea();
String areaStr = df.format(area);
System.out.println("圆的面积为:" + areaStr);
// 求圆的体积并格式化输出
double volume = c.getVolume();
String volumeStr = df.format(volume);
System.out.println("圆的体积为:" + volumeStr);
}
}
```
输出结果为:
```
圆的面积为:78.54
圆的体积为:523.6
```
其中使用了DecimalFormat类的format方法来规范化输出结果的小数位数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)