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


我们可以使用**方法重载**在Java中计算正方形的面积。“方法重载”是Java中的一项特性,允许在一个类中编写多个同名的方法。它使我们能够声明多个同名但签名不同的方法,即方法的参数数量可能不同,或者参数的数据类型可能不同。方法重载有助于提高代码的可读性,以便我们可以以不同的方式使用相同的方法。

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

正方形的面积

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

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

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

算法

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

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

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

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

示例

在这个示例中,我们使用基本公式计算正方形的面积,并在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)

示例

在这个示例中,我们使用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中实现方法重载。

更新于:2023年4月11日

1000+ 次浏览

启动您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.