Java用方法重载求矩形 圆和三角形的面积
时间: 2023-05-18 20:03:10 浏览: 301
可以使用方法重载来求解矩形、圆和三角形的面积。具体实现如下:
// 计算矩形面积
public static double getArea(double length, double width) {
return length * width;
}
// 计算圆形面积
public static double getArea(double radius) {
return Math.PI * radius * radius;
}
// 计算三角形面积
public static double getArea(double base, double height) {
return 0.5 * base * height;
}
注意:以上代码仅为示例,实际应用中需要根据具体需求进行修改和完善。
相关问题
利用方法重载实现分别求矩形面积、圆形面积和三角形面积
在Java等支持方法重载的语言中,你可以创建一系列同名的方法,每个方法接收不同的参数,以适应计算不同形状的面积。以下是通过方法重载分别求矩形、圆形和三角形面积的例子:
```java
public class ShapeArea {
// 矩形面积
public double getRectangleArea(double length, double width) {
return length * width;
}
// 圆形面积
public double getCircleArea(double radius) {
return Math.PI * radius * radius;
}
// 三角形面积
public double getTriangleArea(double base, double height) {
return 0.5 * base * height;
}
}
```
在这个例子中,`getArea`方法有不同的版本,分别对应矩形的长宽、圆的半径以及三角形的底边和高。当你需要计算某个形状的面积时,只需传入相应的尺寸,系统会自动选择正确的函数进行计算。
用JAVA重载编写圆,三角形,矩形面积
圆的面积:
```
public class Circle {
public double area(double radius) {
return Math.PI * radius * radius;
}
}
```
三角形的面积:
```
public class Triangle {
public double area(double base, double height) {
return 0.5 * base * height;
}
}
```
矩形的面积:
```
public class Rectangle {
public double area(double length, double width) {
return length * width;
}
}
```
阅读全文
相关推荐
















