我們可以用方法來重載在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中文網其他相關文章!