原文: https://beginnersbook.com/2017/09/java-program-to-find-area-of-geometric-figures-using-method-overloading/

该程序使用方法重载找到正方形,矩形和圆形的面积。在这个程序中,我们有三个同名的方法area(),这意味着我们正在重载area()方法。通过面积方法的三种不同实现,我们计算方形,矩形和圆形的面积。

要理解这个程序,你应该具备以下核心 Java 主题的知识:
Java 中的方法重载

示例:使用方法重载编程以查找方形,矩形和圆的面积

  1. class JavaExample
  2. {
  3. void calculateArea(float x)
  4. {
  5. System.out.println("Area of the square: "+x*x+" sq units");
  6. }
  7. void calculateArea(float x, float y)
  8. {
  9. System.out.println("Area of the rectangle: "+x*y+" sq units");
  10. }
  11. void calculateArea(double r)
  12. {
  13. double area = 3.14*r*r;
  14. System.out.println("Area of the circle: "+area+" sq units");
  15. }
  16. public static void main(String args[]){
  17. JavaExample obj = new JavaExample();
  18. /* This statement will call the first area() method
  19. * because we are passing only one argument with
  20. * the "f" suffix. f is used to denote the float numbers
  21. *
  22. */
  23. obj.calculateArea(6.1f);
  24. /* This will call the second method because we are passing
  25. * two arguments and only second method has two arguments
  26. */
  27. obj.calculateArea(10,22);
  28. /* This will call the second method because we have not suffixed
  29. * the value with "f" when we do not suffix a float value with f
  30. * then it is considered as type double.
  31. */
  32. obj.calculateArea(6.1);
  33. }
  34. }

输出:

  1. Area of the square: 37.21 sq units
  2. Area of the rectangle: 220.0 sq units
  3. Area of the circle: 116.8394 sq units