首页 > 编程 > Java > 正文

Java_一个有趣的重载函数栗子

2019-11-06 07:12:17
字体:
来源:转载
供稿:网友

今天主要想讨论一下C++时我就很迷糊的重载函数的概念

java是支持重载的,我们通过一个简单的栗子来看一下它的机制

package float_or_double;public class FloatOrDouble { public static void aMethod(int a){ System.out.PRintln("a="+a+" and is the int one!"); } public static void aMethod(float a){ System.out.println("a="+a+" and is the float one!"); } public static void aMethod(double a){ System.out.println("a="+a+" and is the double one!"); } public static void aMethod(char a){ System.out.println("a="+a+" and is the char one!"); } public static void main(String args[]){ aMethod(3.5); aMethod(3.50); aMethod(3.); aMethod(3d); aMethod(3f); aMethod(3); aMethod('c'); }}

可以看到,我声明了4个重载函数,每一个对应的形参都不同,分别为int,float,double,char

程序输出结果为

a=3.5 and is the double one!a=3.5 and is the double one!a=3.0 and is the double one!a=3.0 and is the double one!a=3.0 and is the float one!a=3 and is the int one!a=c and is the char one!

Java将数字后面有小数点的统一解释为double,而要想调用形参为float的需要在数字后面注明’f’

查找资料后得知: 对编程人员来说,double 和 float 的区别是double精度高,有效数字16位,float精度7位。但double消耗内存是float的两倍,double的运算速度比float慢得多,java语 言中数学函数名称double 和 float不同,不要写错,能用单精度时不要用双精度(以省内存,加快运算速度)

(1)float型 内存分配4个字节,占32位,范围从10^-38到10^38 和 -10^38到-10^-38 例float x=123.456f,y=2e20f; 注意float型定义的数据末尾必须有”f”或”F”,为了和double区别

(2)double型 内存分配8个字节,范围从10^-308到10^308 和 -10^-308到-10^-308 例double x=1234567.98,y=8980.09d; 末尾可以有”d”也可以不写

单精度浮点数在机内占4个字节,用32位二进制描述。 双精度浮点数在机内占8个字节,用64位二进制描述。

有趣的是,当我删去形参为int的重载函数后,如果数字后面没有小数点,则将自动解释为float类型

代码如下

package float_or_double;public class FloatOrDouble { /*public static void aMethod(int a){ System.out.println("a="+a+" and is the int one!"); }*/ public static void aMethod(float a){ System.out.println("a="+a+" and is the float one!"); } public static void aMethod(double a){ System.out.println("a="+a+" and is the double one!"); } public static void aMethod(char a){ System.out.println("a="+a+" and is the char one!"); } public static void main(String args[]){ aMethod(3.5); aMethod(3.50); aMethod(0.0); aMethod(0); aMethod(0.); aMethod(3d); aMethod(3f); aMethod(3); aMethod('c'); }}

输出结果为

a=3.5 and is the double one!a=3.5 and is the double one!a=0.0 and is the double one!a=0.0 and is the float one!a=0.0 and is the double one!a=3.0 and is the double one!a=3.0 and is the float one!a=3.0 and is the float one!a=c and is the char one!

一个小彩蛋,Java中char类型是可以参与运算的,如将形参为char的重载函数改为如下形式:

public static void aMethod(char a){ System.out.println("a="+(a+1)+" and is the char one!"); }

那么会输出a=100 and is the char one!,可以看到,’c’参与到了计算中,结果为ascii码+1


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表