Java 中方法重载(Method Overloading)是一种重要特性,它允许在同一个类中创建多个方法,只要它们参数列表不同即可。参数列表的不同,可以体现在参数数量、参数类型或参数的顺序上,方法重载可以提高代码的灵活性和可读性。
重载特征
方法名相同
方法参数类型,参数个数或顺序不同
方法的返回类型可以不相同
方法的修饰符可以不相同
示例:
public class MethodOverloadingExample {
// 重载方法1:没有参数
public void display() {
System.out.println("Display method called with no parameters.");
}
// 重载方法2:一个整数参数
public void display(int a) {
System.out.println("Display method called with one integer parameter: " + a);
}
// 重载方法3:两个整数参数
public void display(int a, int b) {
System.out.println("Display method called with two integer parameters: " + a + ", " + b);
}
// 重载方法4:一个字符串参数
public void display(String s) {
System.out.println("Display method called with one string parameter: " + s);
}
// 重载方法5:一个整数和一个字符串参数
public void display(int a, String s) {
System.out.println("Display method called with one integer and one string parameter: " + a + ", " + s);
}
public static void main(String[] args) {
MethodOverloadingExample obj = new MethodOverloadingExample();
// 调用不同的重载方法
obj.display();
obj.display(10);
obj.display(10, 20);
obj.display("Hello");
obj.display(30, "World");
}
}
结果:
Display method called with no parameters.
Display method called with one integer parameter: 10
Display method called with two integer parameters: 10, 20
Display method called with one string parameter: Hello
Display method called with one integer and one string parameter: 30, World
469

被折叠的 条评论
为什么被折叠?



