我们可以使用方法重载在Java中计算矩形的面积。 "方法重载"是Java中的一个特性,它允许在同一个类中使用相同的方法名编写多个方法。这将使我们能够声明多个具有相同名称但具有不同签名的方法,即方法中的参数数量可能不同或参数的数据类型可能不同。方法重载帮助我们增加代码的可读性,以便我们可以以不同的方式使用相同的方法。
Now, let us achieve Method Overloading in Java by considering the “area of a rectangle” as an example.
Area of a rectangle is defined region occupied by ait in a 2-d plane. We can find the area of rectangle by performing the product of length and breadth of rectangle.
Area of Rectangle = lb where l: length of rectangle. b: breadth of rectangle
In the below example, we will achieve Method Overloading in Java using the area of a rectangle as an example by changing the data types of parameters.
STEP 1 − Write a custom class to find the area of the rectangle.
STEP 2 − Initialize a pair of two variables of different data types in the main method of the public class.
STEP 3 − Create an object of a custom class in the main method of the public class.
STEP 4 − Call the specific method to find the area of the rectangle using the custom object created.
在这个例子中,我们使用一个基本公式计算矩形的面积,并在Java中实现了方法重载。
方法重载是通过改变“areaOfRectangle”方法中参数的类型来实现的。现在,当用户将整数类型的参数值作为输入传递给areaOfRectangle方法时,Area类的第一个areaOfRectangle方法被调用并输出结果。如果用户输入的是双精度类型的参数,则调用并执行第二个areaOfRectangle方法。
//Java Code to achieve Method Overloading in Java by Area of Rectangle. import java.io.*; class Area { // In this example area method is overloaded by changing the type of parameters. public void areaOfRectangle(int length, int breadth) { int area = 0; area = length *breadth; System.out.println("Area of the rectangle is :" + area); } public void areaOfRectangle(double length, double breadth) { double area= 0; area = length *breadth; System.out.println("Area of the rectangle is:" + area); } } public class Main { public static void main(String args[]) { Area Object = new Area(); int length_1 = 3; int breadth_1 = 4; Object.areaOfRectangle(length_1, breadth_1); double length_2 = 4.5; double breadth_2 = 5.5; Object.areaOfRectangle(length_2, breadth_2); } }
Area of the rectangle is :12 Area of the rectangle is:24.75
Time Complexity: O(1) Auxiliary Space: O(1)
Thus, in this article, we have learned how to implement Method Overloading in Java by changing the datatype of parameters using the example of finding the area of a rectangle.
以上是使用方法重载来查找矩形面积的Java程序的详细内容。更多信息请关注PHP中文网其他相关文章!