🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# Java 程序:使用方法重载查找几何图形的面积 > 原文: [https://beginnersbook.com/2017/09/java-program-to-find-area-of-geometric-figures-using-method-overloading/](https://beginnersbook.com/2017/09/java-program-to-find-area-of-geometric-figures-using-method-overloading/) 该程序使用方法重载找到正方形,矩形和圆形的面积。在这个程序中,我们有三个同名的方法`area()`,这意味着我们正在重载`area()`方法。通过面积方法的三种不同实现,我们计算方形,矩形和圆形的面积。 要理解这个程序,你应该具备以下[核心 Java](https://beginnersbook.com/java-tutorial-for-beginners-with-examples/) 主题的知识: [Java 中的方法重载](https://beginnersbook.com/2013/05/method-overloading/) ## 示例:使用方法重载编程以查找方形,矩形和圆的面积 ```java class JavaExample { void calculateArea(float x) { System.out.println("Area of the square: "+x*x+" sq units"); } void calculateArea(float x, float y) { System.out.println("Area of the rectangle: "+x*y+" sq units"); } void calculateArea(double r) { double area = 3.14*r*r; System.out.println("Area of the circle: "+area+" sq units"); } public static void main(String args[]){ JavaExample obj = new JavaExample(); /* This statement will call the first area() method * because we are passing only one argument with * the "f" suffix. f is used to denote the float numbers * */ obj.calculateArea(6.1f); /* This will call the second method because we are passing * two arguments and only second method has two arguments */ obj.calculateArea(10,22); /* This will call the second method because we have not suffixed * the value with "f" when we do not suffix a float value with f * then it is considered as type double. */ obj.calculateArea(6.1); } } ``` **输出:** ```java Area of the square: 37.21 sq units Area of the rectangle: 220.0 sq units Area of the circle: 116.8394 sq units ```