您的位置:首页 > 编程语言 > Java开发

java之如何区分重载函数

2015-02-24 16:29 225 查看
转载请注明出处

/article/1371496.html

作者:小马


一 通过函数返回值?

想想似乎可以,比如,

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 stub
		PrimitiveOverloading p = new PrimitiveOverloading();
		p.testConstVal();
		p.testChar();
		p.testByte();
		p.testShort();
		p.testInt();
		p.testLong();

	}

}


输出结果,

Testing with 5
f1(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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: