首页 > 编程知识 正文

重载函数的特性总结为,重载函数的特性总结表

时间:2023-05-04 06:28:22 阅读:262943 作者:113

重载函数的一些总结 直接show code + 个人总结

①重载函数可以区分拆装箱
重载方法的调用过程中,入参数据如果有基本类型不再装拆箱,因为重载可以区分入参对象是基本类型还是对象类型,下例可以体现出来:

package test;public class Override { public static void f(int a){ System.out.println("int"); } public static void f(Integer a){ System.out.println("Integer"); } public static void main(String[] args) { int intA = 10; Integer integerA = 10; f(intA); f(integerA); }}//输出://int//Integer

②重载函数入参都有Object…对象时,就无法通过入参拆装箱来选择哪一个重载函数

public class Override { public static void f(int a, Object...objects){ System.out.println("int"); } public static void f(Integer a, Object...objects){ System.out.println("Integer"); } public static void main(String[] args) { int intA = 10; Integer integerA = 10; f(intA);//The method f(int, Object[]) is ambiguous for the type Override f(integerA);//The method f(int, Object[]) is ambiguous for the type Override }}

上面的这个例子,调用重载函数的时候都会报错。如果重载函数没有Object…那么可以通过区分入参对象是否拆装箱来实现重载,但是入参如果有Object…则无法通过入参对象是否拆装箱来区分了。
具体原因应该是涉及到JVM的原理了。

③重载函数面对两个方法都符合的入参,会优先选择更准确的方法。

public class Override { public static void f(int a){ System.out.println("int"); } public static void f(Integer a, Object...objects){ System.out.println("Integer"); } public static void main(String[] args) { int intA = 10; Integer integerA = 10; f(intA); f(integerA); }}//输出://int//int

同样的,如果重载函数改为f(int a, Object…objects)和f(Integer a),那么最后的输出结果为Integer Integer。
虽然理论上两个重载函数的入参都符合f(intA)和f(integerA)但是JVM却选择了没有Object…的重载函数。建立在都符合入参的情况下JVM会去选择更准确的重载方法。
这里还可以得出函数重载时考虑的优先级:不定长度>拆装箱

④重载函数无法将基本数据类型和Object…区分开
入参对象有对象(装箱)型Integer,如上述总结③得出的,优先使用有Integer的重载函数

public class Override { public static void fff(Object...objects) { System.out.println("Object..."); } public static void fff(Integer b, Object...objects) { System.out.println("Integer,Obeject..."); } public static void main(String[] args) { fff(10); }}//Integer,Obeject...

如果入参对象有个基本数据类型int/double/long/float/char….,则会报错

public class Override { public static void fff(Object...objects) { System.out.println("Object..."); } public static void fff(int b, Object...objects) { System.out.println("int,Obeject..."); } public static void main(String[] args) { fff(10);//The method fff(Object[]) is ambiguous for the type Override }} 目前总结出来四点

①重载函数可以区分拆装箱
②重载函数入参都有Object…对象时,就无法通过入参拆装箱来选择哪一个重载函数。
③重载函数面对两个方法都符合的入参,会优先选择更准确的方法。
④重载函数无法将基本数据类型和Object…区分开

可以根据 实例+总结 再思考一下,这些特征的共同点,我们知道重载的使用主要是为了提升函数的复用,准确的说是函数名,他是针对【函数名+不同的入参】来区分该调用哪个方法。上述总结除了①,都是因为入参加入了Object…才出现的现象,这些特性还是在实践中所得。思考其面对Object…入参处理的特性,应该涉及到JVM函数载入过程中的选择,也可能是在项目编译的过程中的一些特性。还需要继续去探索。

总之最后一句,不建议在重载函数中使用Object…,除非彻底摸清楚重载函数调用过程针对Object…入参的处理方式。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。