在 Java 中,方法多載是一項功能,讓同一個類別可以有多個同名的方法,只要它們的參數列不同就好。 它與編譯時期(或靜態)多型有關。 想要建立執行相似工作、但輸入不同的方法,就要先了解這個概念。
方法多載能提升程式的可讀性。 不同的方法可以取相同的名稱,但使用不同的參數。 程式會根據參數的數量或參數的型態,呼叫對應的方法。
方法多載的關鍵在於方法的簽章。 如果兩個方法的簽章不同,就會被視為不同的方法。 方法多載有兩種方式:
參數數量不同:方法可以同名,但參數數量不同。
public class Display {
public void show(int x) {
System.out.println("Show with int: " + x);
}
public void show(int x, int y) {
System.out.println("Show with two ints: " + x + ", " + y);
}
}
參數型態不同:方法可以同名、參數數量也相同,但型態不同。
public class Display {
public void show(int x) {
System.out.println("Show with int: " + x);
}
public void show(String s) {
System.out.println("Show with String: " + s);
}
}
在這個概念中,我們會一起看看 Java 中方法多載的各種範例與細節喔。
在這個練習中,你會和最好的朋友一起玩一款名為「Wizard and Warriors」的角色扮演遊戲。 你是遊戲主持人,負責讓遊戲世界在玩家眼前鮮活起來。 其中一個關鍵在於向玩家描述遊戲:角色的狀態是什麼、他們造訪的城鎮長什麼樣子等等。
你有五項任務,要分別向玩家描述遊戲的各個部分。
每個角色都有類別、等級和生命值,描述方式如下:"You're a level <LEVEL> <CLASS> with <HIT_POINTS> hit points."。
請實作GameMaster.describe方法,它只接受一個Character參數,並回傳該角色的描述。
Character character = new Character();
character.setCharacterClass("Wizard");
character.setLevel(4);
character.setHitPoints(28);
new GameMaster().describe(character);
// => "You're a level 4 Wizard with 28 hit points."
每個目的地都有名稱和居民人數,描述方式如下:"You've arrived at <NAME>, which has <INHABITANTS> inhabitants."。
請實作GameMaster.describe方法,它只接受一個Destination參數,並回傳該目的地的描述。
Destination destination = new Destination();
destination.setName("Muros");
destination.setInhabitants(732);
new GameMaster().describe(destination);
// => "You've arrived at Muros, which has 732 inhabitants."
角色可以用下列兩種方式的其中一種前往目的地:
"You're traveling to your destination by walking."
"You're traveling to your destination on horseback."
請實作GameMaster.describe方法,它只接受一個TravelMethod參數,並回傳該旅行方式的描述。
new GameMaster().describe(TravelMethod.HORSEBACK);
// => "You're traveling to your destination on horseback."
當角色前往某個目的地時,描述方式是個別描述的組合:"<CHARACTER> <TRAVEL_METHOD> <DESTINATION>"。
請實作GameMaster.describe方法,它接受一個Character、一個Destination和一個TravelMethod參數,並回傳該描述。
Character character = new Character();
character.setCharacterClass("Wizard");
character.setLevel(4);
character.setHitPoints(28);
Destination destination = new Destination();
destination.setName("Muros");
destination.setInhabitants(732);
new GameMaster().describe(character, destination, TravelMethod.HORSEBACK);
// => "You're a level 4 Wizard with 28 hit points. You're traveling to your destination on horseback. You've arrived at Muros, which has 732 inhabitants."
大多數情況下,角色都是以步行前往目的地。
為了方便,玩家可以省略旅行方式;在這種情況下,會假設旅行方式為步行。
請實作GameMaster.describe方法,它接受一個Character和一個Destination參數,並回傳該描述。
Character character = new Character();
character.setCharacterClass("Wizard");
character.setLevel(4);
character.setHitPoints(28);
Destination destination = new Destination();
destination.setName("Muros");
destination.setInhabitants(732);
new GameMaster().describe(character, destination);
// => "You're a level 4 Wizard with 28 hit points. You're traveling to your destination by walking. You've arrived at Muros, which has 732 inhabitants."