首页 > 文章列表 > 使用方法重载找到正方形面积的Java程序

使用方法重载找到正方形面积的Java程序

方法重载 面积 正方形
429 2023-09-01

我们可以使用方法重载来计算Java中正方形的面积。“方法重载”是Java中的一项功能,允许人们使用相同的方法在同一个类中编写多个方法姓名。它将使我们能够声明多个具有相同名称但具有不同签名的方法,即方法中的参数数量可能不同或参数的数据类型可能不同。方法重载帮助我们增加代码的可读性,以便我们可以以不同的方式使用同一个方法。

现在,让我们以“正方形的面积”为例,在Java中实现方法重载。

正方形的面积

正方形的面积是在二维平面上所占据的定义区域。我们可以通过边长*边长的乘积来计算正方形的面积。

Area of Square =  s*s
where	 
s: side of square                              

在下面的例子中,我们将以正方形的面积为例,通过改变参数的数据类型来实现Java中的方法重载。

算法

第 1 步 - 编写一个自定义类来查找正方形的面积。

STEP 2 - 在公共类的 main 方法中初始化一对不同数据类型的两个变量。

步骤 3 - 在公共类的主方法中创建一个自定义类的对象。

步骤4 − 调用特定方法,使用创建的自定义对象来找到正方形的面积。

Example

的中文翻译为:

示例

在此示例中,我们使用基本公式计算正方形的面积,并在 Java 中实现方法重载。

方法重载是通过改变“areaOfSquare”方法中的参数类型来实现的。现在,当用户将整数类型的参数值输入给areaOfSquare方法时,Area类的第一个areaOfSquare方法被调用并输出结果。如果用户输入的是双精度类型的参数,则调用并执行第二个areaOfSquare方法。

//Java Code to achieve Method Overloading in Java by Area of Square.
import java.io.*;
class Area {
   // In this example area method is overloaded by changing the type of parameters.
   public void areaOfSquare(int side) {
      int area = 0;
      area = side * side;
      System.out.println("Area of the square is :" + area);
   }
   public void areaOfSquare(double side) {
      double area= 0;
      area = side*side;
      System.out.println("Area of the square is:" + area);
   }
}
public class Main {
   public static void main(String args[]) {
      Area Object  = new Area();
      int side_1= 3;
      Object.areaOfSquare(side_1);
      double side_2 = 4.5;
      Object.areaOfSquare(side_2);
   }
}

输出

Area of the square is :9
Area of the square is:20.25                             

时间复杂度:O(1) 辅助空间:O(1)

Example

的中文翻译为:

示例

在这个例子中,我们使用Math.pow()函数计算正方形的面积,并在Java中实现方法重载。

方法重载是通过改变“areaOfSquare”方法中的参数类型实现的。现在,当用户将整数类型的参数值输入给areaOfSquare方法时,Area类的第一个areaOfSquare方法被调用并输出结果。如果用户输入的是双精度类型的参数,则调用并执行第二个areaOfSquare方法。

//Java Code to achieve Method Overloading in Java by Area of Square.
import java.io.*;
class Area {
   // In this example area method is overloaded by changing the type of parameters.
   public void areaOfSquare(int side) {
      int area = 0;
      area =(int) Math.pow(side,2);
      System.out.println("Area of the square is :" + area);
   }
   public void areaOfSquare(double side) {
      double area= 0;
      area = Math.pow(side,2);
      System.out.println("Area of the square is:" + area);
   }
}
public class Main {
   public static void main(String args[]) {
      Area Object  = new Area();
      int side_1= 3;
      Object.areaOfSquare(side_1);
      double side_2 = 4.5;
      Object.areaOfSquare(side_2);
   }
}

输出

Area of the square is :9
Area of the square is:20.25                            

时间复杂度:O(1) 辅助空间:O(1)

因此,在本文中,我们以求正方形面积为例,学习了如何通过更改参数的数据类型来实现 Java 中的方法重载。