Java重载overload
发布日期:2021-05-07 14:40:44 浏览次数:10 分类:原创文章

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

目录


1 重载(Overload)

   在一个类中,同名的方法如果有不同的参数列表(参数类型不同、参数个数不同甚至是参数顺序不同)则视为重载。同时,重载对返回类型没有要求,可以相同也可以不同,但不能通过返回类型是否相同来判断重载。 

      1.不同的含义:形参类型、形参个数、形参顺序不同

      2.只有返回值不同不构成方法的重载

      如:

int a(String str){}与 void a(String str){}

      不构成方法重载

      3.只有形参的名称不同,不构成方法的重载

      如:

int a(String str){}与int a(String s){}

      不构成方法重载

1.1 方法重载实例

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) {        int sum = n1 + n2;        return sum;    }    // 方法名相同,参数个数不同,构成重载    public static int add(int n1, int n2, int n3) {        int sum = n1 + n2 + n3;        return sum;    }    // 方法名相同,参数类型不同,构成重载    public static double add(double n1, int n2) {        double sum = n1 + n2;        return sum;    }    // 方法名相同,参数顺序不同,构成重载    public static double add(int n1, double n2) {        double sum = n1 + n2;        return sum;    }    //编译错误:只有返回值不同,不构成方法的重载    public static double add(int n1, int n2) {        double sum = n1 + n2;        return sum;    }    //编译错误:只有参数名称不同,不构成方法的重载    public static int add(int n2, int n1) {        double sum = n1 + n2;                 return sum;    }}

运行效果:

2 总结

 

  1. 重载Overload是一个类中多态性的一种表现 
  2. 重载要求同名方法的参数列表不同(参数类型,参数个数甚至是参数顺序) 
  3. 重载的时候,返回值类型可以相同也可以不相同。无法以返回型别作为重载函数的区分标准
上一篇:JAVA递归算法
下一篇:JAVA方法的定义

发表评论

最新留言

路过按个爪印,很不错,赞一个!
[***.219.124.196]2025年03月19日 18时37分07秒