现在,让我们以“正方形的面积”为例,在java中实现方法重载。
正方形的面积正方形的面积是在二维平面上所占据的定义区域。我们可以通过边长*边长的乘积来计算正方形的面积。
area of square = s*swhere 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 :9area 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 :9area of the square is:20.25
时间复杂度:o(1) 辅助空间:o(1)
因此,在本文中,我们以求正方形面积为例,学习了如何通过更改参数的数据类型来实现 java 中的方法重载。
以上就是使用方法重载找到正方形面积的java程序的详细内容。
