博客
关于我
Java重载overload
阅读量:357 次
发布时间:2019-03-04

本文共 1466 字,大约阅读时间需要 4 分钟。

方法重载(Overload)解析

定义与特点

在一个类中,若存在同名的方法但参数列表有所不同(包括参数类型、个数甚至顺序),则称为重载。重载对返回类型没有要求,无论是否相同都视为不同的方法,且不能仅凭返回类型判断重载。

重载的含义

  • 参数的不同:参数类型、个数或顺序的任何不同都构成重载。

    • 例如:int a(String str) 和 void a(String str) 是不同的方法,属于重载。
  • 返回值无关:仅返回值不同不能构成重载。

    • 例如:int a(String str) 和 double a(String str) 是不同的方法,属于重载。
  • 参数名称无关:参数名称的不同不会导致重载。

    • 例如:int a(String str) 和 int a(String s) 是同一个方法的重载形式。
  • 实例分析

    以下示例展示了方法重载的应用:

    public class Test {    public static void main(String[] args) {        System.out.println(add(3, 5));      // 8        System.out.println(add(3, 5, 10)); // 18        System.out.println(add(3.0, 5));    // 8.0        System.out.println(add(3, 5.0));    // 8.0                System.out.println();                 // 0个参数        System.out.println(1);                 // 1个参数,int类型        System.out.println(3.0);               // 1个参数,double类型    }        public static int add(int n1, int n2) {        return n1 + n2;    }        public static int add(int n1, int n2, int n3) {        return n1 + n2 + n3;    }        public static double add(double n1, int n2) {        return n1 + n2;    }        public static double add(int n1, double n2) {        return n1 + n2;    }        // 编译错误:仅返回值不同,不构成重载    public static double add(int n1, int n2) {        return n1 + n2;    }        // 编译错误:仅参数名称不同,不构成重载    public static int add(int n2, int n1) {        return n2 + n1;    }}

    总结

    方法重载是Java中多态性的一种表现形式,通过参数列表的差异实现同一方法名的多种实现。重载方法的参数列表必须不同(类型、个数或顺序),而返回类型不能作为判断重载的依据。通过以上分析,可以清晰地理解方法重载的定义、特点及其实际应用。

    转载地址:http://kkzr.baihongyu.com/

    你可能感兴趣的文章
    python3 grpc安装
    查看>>
    python3 mysql 封装多表_python3 mysql-多表查询
    查看>>
    python3 mysql8_Python MySQL8.0 错误:authentication plugin 'calling_sha2_password' is not supported....
    查看>>
    Python关键代码总览!从Zero到Hero必看的考点
    查看>>
    python3 robotframework+pycharm框架搭建
    查看>>
    Python3 shutil模块
    查看>>
    Python关于strftime函数详细解析 附实战代码
    查看>>
    Python3 tutorial day3
    查看>>
    python3 week4
    查看>>
    Python3 创建数组
    查看>>
    python3 套接字异常(a byte-like object is required not str)
    查看>>
    python3 实现用户三次输入错误记录黑名单并对该用户登录锁定-day1
    查看>>
    python3 文本变图片
    查看>>
    Python3 查看 com 组件的属性
    查看>>
    python3 案例分享--发邮件
    查看>>
    python3 模板库_Python3 标准库概览_Python教程_我爱模板网 - 提供下载各种免费建站资源,免费网站模板,免费网页特效,让你爱上建站!...
    查看>>
    Python3 求最大/小值及索引值 Numpy
    查看>>
    python3+django使用celery执行某些任务失败的解决方案
    查看>>
    Python3+Requests+Unittest实战系列【一】
    查看>>
    python3+requests+unittest实战系列【一】
    查看>>