public class Calculator {
public int add(int a, int b) {
return a + b;
}
public double add(double a, double b) {
return a + b;
}
public int add(int a, int b, int c) {
return a + b + c;
}
}
public void print(String s) {}
public void print(int n) {}
public void print(String s, int n) {}
public void print(int n, String s) {}
以上所有方法都是有效的多載範例。Java 編譯器會根據參數的不同判斷應該呼叫哪個方法。
無法多載的情況
相對地,僅僅回傳值型態不同,或只更改參數名稱時,並不構成多載。例如下列定義會產生編譯錯誤:
public int multiply(int a, int b) {}
public double multiply(int a, int b) {} // 只有回傳型態不同 → 錯誤
因為 Java 在方法呼叫時不考慮回傳型態,所以上述情況會導致模糊不清,編譯器不允許這種定義。
3. 多載的使用範例
以加法方法為例的簡單範例
以下示範如何透過參數型態或數量的不同,為同名方法 add 實作多載:
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public double add(double a, double b) {
return a + b;
}
public int add(int a, int b, int c) {
return a + b + c;
}
}
如上,根據不同參數,會自動選擇對應的方法,程式碼更簡潔、直觀。
在類別中的實作範例:顯示用戶資訊
以下為在物件導向類別中實作多載的範例:
public class UserInfo {
public void display(String name) {
System.out.println("姓名: " + name);
}
public void display(String name, int age) {
System.out.println("姓名: " + name + ", 年齡: " + age);
}
public void display(String name, int age, String email) {
System.out.println("姓名: " + name + ", 年齡: " + age + ", 電子郵件: " + email);
}
}
這樣能根據資訊量的多寡選擇不同方法,大幅提升程式碼的可讀性與彈性。
建構子的多載
多載不只適用於方法,也能用於建構子。如以下,根據參數不同執行不同初始化:
public class Product {
private String name;
private int price;
// 預設建構子
public Product() {
this.name = "未設定";
this.price = 0;
}
// 只設定名稱的建構子
public Product(String name) {
this.name = name;
this.price = 0;
}
// 設定名稱和價格的建構子
public Product(String name, int price) {
this.name = name;
this.price = price;
}
}
public void greet(String name) {}
public void greet(String name, int age) {}
→ 因為參數不同,雖然方法名稱相同也視為不同方法
什麼是覆寫?
對象:從父類別(超類別)繼承的方法
目的:在子類別中覆寫父類別的方法行為
條件:
方法名稱、參數、回傳型態都需完全一致
存取修飾詞不能比父類別更嚴格
通常會加上 @Override 註解以明確標示
class Animal {
public void speak() {
System.out.println("動物發出聲音");
}
}
class Dog extends Animal {
@Override
public void speak() {
System.out.println("汪汪!");
}
}