在 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."