一、方法調用的基本語法
在Java中,調用方法的基本語法為:
方法名(參數1, 參數2, ..., 參數n);
其中,方法名
為要調用的方法的名稱,參數
為該方法接收的參數列表。
例如,下面的代碼演示了一個簡單的方法調用:
public class MethodExample { public static void main(String[] args) { int result = add(1, 2); System.out.println("1 + 2 = " + result); } public static int add(int a, int b) { return a + b; } }
運行結果為:
1 + 2 = 3
在上面的代碼中,調用了一個名為add
的靜態方法,將1和2作為參數傳入,並將結果保存在result
變量中。
二、方法的重載
在Java中,可以定義多個同名的方法,只要它們的參數列表不同就可以。這種方法稱為方法的重載。
例如,有兩個方法分別接收一個整數和一個字符串:
public class OverloadExample { public static void main(String[] args) { int result1 = add(1, 2); String result2 = add("Hello, ", "World!"); System.out.println(result1); System.out.println(result2); } public static int add(int a, int b) { return a + b; } public static String add(String a, String b) { return a + b; } }
運行結果為:
3 Hello, World!
在上面的代碼中,定義了兩個名為add
的方法,分別接收兩個整數和兩個字符串作為參數,並返回它們的和及拼接結果。
三、方法的覆蓋
在Java中,如果一個類繼承自另一個類,可以在子類中覆蓋父類的方法。被覆蓋的方法稱為父類的方法,覆蓋它的方法稱為子類的方法。
例如,有一個父類和一個子類,它們都定義了一個名為run
的方法:
public class ParentClass { public void run() { System.out.println("Parent is running."); } } public class ChildClass extends ParentClass { public void run() { System.out.println("Child is running."); } }
在上面的代碼中,ChildClass
覆蓋了ParentClass
的run
方法,輸出了不同的內容。
可以使用以下代碼進行測試:
public class OverrideExample { public static void main(String[] args) { ParentClass parent = new ParentClass(); ChildClass child = new ChildClass(); parent.run(); child.run(); } }
運行結果為:
Parent is running. Child is running.
四、接口方法的實現
在Java中,接口是一種特殊的類,其中只包含抽象方法和常量。實現接口的類必須實現接口中定義的所有方法。這些方法稱為接口方法。
例如,有一個名為Runnable
的接口,其中定義了一個run
方法:
public interface Runnable { public void run(); }
如果要實現該接口,必須實現run
方法。例如:
public class ThreadExample implements Runnable { public static void main(String[] args) { Thread thread = new Thread(new ThreadExample()); thread.start(); System.out.println("Thread is running."); } public void run() { System.out.println("Thread is running."); } }
運行結果為:
Thread is running. Thread is running.
在上面的代碼中,ThreadExample
實現了Runnable
接口,並覆蓋了其中的run
方法。在main
方法中,創建了一個新的線程並啟動它,該線程將執行ThreadExample
實現的run
方法。
五、Lambda表達式調用方法
在Java 8中,引入了Lambda表達式,可以在代碼中使用它們來調用方法。
例如,定義一個接口和一個包含該接口方法的類:
public interface Operation { public int operate(int a, int b); } public class Calculator { public int add(int a, int b) { return a + b; } public int subtract(int a, int b) { return a - b; } }
可以使用Lambda表達式調用這些方法,例如:
public class LambdaExample { public static void main(String[] args) { Calculator calculator = new Calculator(); int result1 = calculator.add(1, 2); System.out.println(result1); Operation operation = (a, b) -> a - b; int result2 = operation.operate(3, 4); System.out.println(result2); } }
運行結果為:
3 -1
在上面的代碼中,首先調用了Calculator
中的add
方法。然後,使用Lambda表達式定義了一個名為operation
的Operation
對象,它實現了operate
方法並返回兩個整數的差。最後,使用operation
對象調用operate
方法。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/180332.html