【正文】
{ 21 CRectangle rect1。 22 rect1=new CRectangle()。 //創(chuàng)建新的對象 23 24 =10。 //賦值長方形 rect1的寬 25 =5。 // 賦值長方形 rect1的高 26 27 (area=+())。 28 (perimeter=+())。 29 } 30 } /* app73 OUTPUT area=50 perimeter=30 */ 方法的運行過程 例 max方法 ? public class TestMax ? { ? // Main method ? public static void main(String[] args) ? { ? int i = 5。 ? int j = 2。 ? int k = max(i, j)。 ? (The maximum between + i + ? and + j + is + k)。 ? } ? static int max(int num1, int num2) ? { ? if (num1 num2) ? return num1。 ? else ? return num2。 ? } ? } 參數(shù)的傳遞 方法的威力是它處理參數(shù)的能力。調(diào)用方法時,需要提供實參,他們必須與方法中所對應的形參次序相同,這叫參數(shù)順序匹配。 void nPrintln(String message, int n) { for (int i=0。 in。 i++) (message)。 } 參數(shù)按值傳遞 在調(diào)用帶參數(shù)的方法時,實參的值復制到方法中稱為值傳遞。無論方法中的形參怎樣變化,方法外的實參不受影響。 例 ? public class TestPassByValue ? { ? // Main method ? public static void main(String[] args) ? { ? // Declare and initialize variables ? int num1 = 1。 ? int num2 = 2。 ? ? (Before invoking the swap method, num1 is + ? num1 + and num2 is + num2)。 ? // Invoke the swap method to attempt to swap two variables ? swap(num1, num2)。 ? (After invoking the swap method, num1 is + ? num1 + and num2 is + num2)。 ? } ? 例 // The method for swapping two variables ? static void swap(int n1, int n2) ? { ? ( Inside the swap method)。 ? ( Before swapping n1 is + n1 ? + n2 is + n2)。 ? ? // Swapping n1 with n2 ? int temp = n1。 ? n1 = n2。 ? n2 = temp。 ? ? ( After swapping n1 is + n1 ? + n2 is + n2)。 ? } ? } 45方法重載 方法重載的意思是: 一個類中可以有多個方法具有相同的名字,但這些方法的參數(shù)必須不同,即或者是參數(shù)的個數(shù)不同,或者是參數(shù)的類型不同。 例: double max(double num1, double num2) { if (num1 num2) return num1。 else return num2。 } 例 max方法 ? public class TestMethodOverloading ? { ? // Main method ? public static void main(String[] args) ? { ? // Invoke the max method with int parameters ? (The maximum between 3 and 4 is ? + max(3, 4))。 ? ? // Invoke the max method with the double parameters ? (The maximum between and is ? + max(, ))。 ? ? // Invoke the max method with three do