java之如何区分重载函数

来源:互联网 发布:手机怎么搜淘宝店铺号 编辑:程序博客网 时间:2024/06/01 14:40

转载请注明出处

http://blog.csdn.net/pony_maggie/article/details/43925705


作者:小马

 

一 通过函数返回值?

想想似乎可以,比如,

void f() {}int f() {}

 

调用时,

int x = f();


编译器应该是可以判断出该调用哪个函数的? 我们忽略了一种情况,有时候不在意某个函数的返回值,也就不用变量来保存,比如这样调用,

f();

 

编译器会晕不知道该调用哪个。所以通过函数返回值无法区分重载函数。


二 通过不同的参数
这个明显可以,很多编译语言都是用这种机制,比如

void f1(char x) {prt("f1(char)");}void f1(String x) {prt("f1(String)");}

 

调用,

f1('x');//第一个f1("aabb"); //第二个


再思考一个问题,java的基本类型存在类型转换的问题,提升或者截断。如果一个char型的实参传入一个int型形参函数中,会发生什么? 下面代码的输出结果可以得出结论。

 

public class PrimitiveOverloading {static void prt(String s){System.out.println(s);}void f1(char x) {prt("f1(char)");}void f1(byte x) {prt("f1(byte)");}void f1(short x) {prt("f1(short)");}void f1(int x) {prt("f1(int)");}void f1(long x) {prt("f1(long)");}void f2(byte x) {prt("f2(byte)");}void f2(short x) {prt("f2(short)");}void f2(int x) {prt("f2(int)");}void f2(long x) {prt("f2(long)");}void f3(short x) {prt("f3(short)");}void f3(int x) {prt("f3(int)");}void f3(long x) {prt("f3(long)");}void f4(int x) {prt("f4(int)");}void f4(long x) {prt("f4(long)");}void f5(int x) {prt("f5(int)");}void f5(long x) {prt("f5(long)");}void testConstVal(){prt("Testing with 5");f1(5);f2(5);f3(5);f4(5);f5(5);}void testChar(){char x = 'x';prt("char argument:");f1(x);f2(x);f3(x);f4(x);f5(x);}void testByte(){byte x = 0;prt("byte argument:");f1(x);f2(x);f3(x);f4(x);f5(x);}void testShort(){short x = 0;prt("short argument:");f1(x);f2(x);f3(x);f4(x);f5(x);}void testInt(){int x = 0;prt("int argument:");f1(x);f2(x);f3(x);f4(x);f5(x);}void testLong(){long x = 0;prt("long argument:");f1(x);f2(x);f3(x);f4(x);f5(x);}/** * @param args */public static void main(String[] args) {// TODO Auto-generated method stubPrimitiveOverloading p = new PrimitiveOverloading();p.testConstVal();p.testChar();p.testByte();p.testShort();p.testInt();p.testLong();}}


输出结果,

Testing with 5f1(int)f2(int)f3(int)f4(int)f5(int)char argument:f1(char)f2(int)f3(int)f4(int)f5(int)byte argument:f1(byte)f2(byte)f3(short)f4(int)f5(int)short argument:f1(short)f2(short)f3(short)f4(int)f5(int)int argument:f1(int)f2(int)f3(int)f4(int)f5(int)long argument:f1(long)f2(long)f3(long)f4(long)f5(long)


 

0 0
原创粉丝点击