Java函數(shù)復寫和重載都是面向?qū)ο缶幊讨谐S玫募夹g,區(qū)別在于復寫是在子類中改寫父類的函數(shù)實現(xiàn),而重載是在同一類中同名函數(shù)的不同實現(xiàn)。
public class Father { public void sayHi() { System.out.println("Hi, I'm Father."); } } public class Son extends Father { public void sayHi() { System.out.println("Hi, I'm Son."); } } Father father = new Father(); Son son = new Son(); father.sayHi(); // Output: "Hi, I'm Father." son.sayHi(); // Output: "Hi, I'm Son."
上述代碼中,子類Son繼承自父類Father,且復寫了sayHi函數(shù)的實現(xiàn),使得在Son類中調(diào)用sayHi時會輸出"Hi, I'm Son."而不是父類中的"Hi, I'm Father."。
而對于重載,只需要在同一類中定義同名但參數(shù)不同的函數(shù)即可。
public class Hello { public void sayHi(String name) { System.out.println("Hi, " + name + "!"); } public void sayHi(String name, int times) { for (int i = 0; i< times; i++) { System.out.println("Hi, " + name + "!"); } } } Hello hello = new Hello(); hello.sayHi("Alice"); // Output: "Hi, Alice!" hello.sayHi("Bob", 2); // Output: "Hi, Bob!" "Hi, Bob!"
在上述代碼中,Hello類定義了兩個同名但參數(shù)不同的函數(shù)sayHi,使得在調(diào)用時可以根據(jù)傳入的參數(shù)類型及數(shù)量來區(qū)分調(diào)用哪個函數(shù)。