Java学习,方法重载

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

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值