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

本文共 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. 重载的时候,返回值类型可以相同也可以不相同。无法以返回型别作为重载函数的区分标准

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

你可能感兴趣的文章
mysql启动报错The server quit without updating PID file几种解决办法
查看>>
MySQL命令行登陆,远程登陆MySQL
查看>>
mysql命令:set sql_log_bin=on/off
查看>>
mySQL和Hive的区别
查看>>
MySQL和Java数据类型对应
查看>>
mysql和oorcale日期区间查询【含左右区间问题】
查看>>
MYSQL和ORACLE的一些操作区别
查看>>
mysql和redis之间互相备份
查看>>
MySQL和SQL入门
查看>>
mysql在centos下用命令批量导入报错_Variable ‘character_set_client‘ can‘t be set to the value of ‘---linux工作笔记042
查看>>
Mysql在Linux运行时新增配置文件提示:World-wrirable config file ‘/etc/mysql/conf.d/my.cnf‘ is ignored 权限过高导致
查看>>
Mysql在Windows上离线安装与配置
查看>>
MySQL在渗透测试中的应用
查看>>
Mysql在离线安装时启动失败:mysql服务无法启动,服务没有报告任何错误
查看>>
Mysql在离线安装时提示:error: Found option without preceding group in config file
查看>>
MySQL基于SSL的主从复制
查看>>
Mysql基本操作
查看>>
mysql基本操作
查看>>
mysql基本知识点梳理和查询优化
查看>>
mysql基础
查看>>