博客
关于我
Java重载overload
阅读量:356 次
发布时间: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/

    你可能感兴趣的文章
    Objective-C实现check strong password检查密码强度算法(附完整源码)
    查看>>
    Objective-C实现chudnovsky algorithm楚德诺夫斯基算法(附完整源码)
    查看>>
    Objective-C实现CIC滤波器(附完整源码)
    查看>>
    Objective-C实现circle sort圆形排序算法(附完整源码)
    查看>>
    Objective-C实现CircularQueue循环队列算法(附完整源码)
    查看>>
    Objective-C实现clearBit清除位算法(附完整源码)
    查看>>
    Objective-C实现climbStairs爬楼梯问题算法(附完整源码)
    查看>>
    Objective-C实现cocktail shaker sort鸡尾酒排序算法(附完整源码)
    查看>>
    Objective-C实现cocktailShakerSort鸡尾酒排序算法(附完整源码)
    查看>>
    Objective-C实现CoinChange硬币兑换问题算法(附完整源码)
    查看>>
    Objective-C实现collatz sequence考拉兹序列算法(附完整源码)
    查看>>
    Objective-C实现Collatz 序列算法(附完整源码)
    查看>>
    Objective-C实现comb sort梳状排序算法(附完整源码)
    查看>>
    Objective-C实现combinationSum组合和算法(附完整源码)
    查看>>
    Objective-C实现combinations排列组合算法(附完整源码)
    查看>>
    Objective-C实现combine With Repetitions结合重复算法(附完整源码)
    查看>>
    Objective-C实现combine Without Repetitions不重复地结合算法(附完整源码)
    查看>>
    Objective-C实现conjugate gradient共轭梯度算法(附完整源码)
    查看>>
    Objective-C实现connected components连通分量算法(附完整源码)
    查看>>
    Objective-C实现Connected Components连通分量算法(附完整源码)
    查看>>