java 重载函数,Java如何选择重载函数来调用?

博客探讨了Java中方法重载的实现原理。当有多个版本的方法,如`doSomething(Base)`和`doSomething(Sub)`,Java编译器会选择最具体的方法。即使变量`ss`是`SubSub`类型,也会调用`doSomething(Sub)`,因为它是更具体的类型。此行为在Java语言规范15.12.2.5部分有详细说明,选择取决于参数类型的最具体匹配,而不是定义顺序。
摘要由CSDN通过智能技术生成

This is a purely theoretical question.

Given three simple classes:

class Base {

}

class Sub extends Base {

}

class SubSub extends Sub {

}

And a function meant to operate on these classes:

public static void doSomething(Base b) {

System.out.println("BASE CALLED");

}

public static void doSomething(Sub b) {

System.out.println("SUB CALLED");

}

It seems that the followign code:

SubSub ss = new SubSub();

doSomething(ss);

could legitimately result in printing either BASE CALLED, or SUB CALLED, since SubSub can be casted to both of those. In fact, removing the Sub version of the function causes BASE CALLED to be printed. What actually happens is that "SUB CALLED" is printed. This seems to mean that which function is called doesn't depend on the order the functions are defined in, as the Base version was called first.

Does Java just look at all the different versions of the function and pick the one which requires the smallest traversal up the inheritance stack? Is this standardized? Is it written out in any documentation?

解决方案

The formal specification can be found in part 15.12.2.5 of the Java Language Specification (JLS). Thanks to generics this is pretty complicated, so you might want to look at same section of the first edition of the JLS.

It basically says that the compiler tries to find a version of the method where all parameters including the object the method is called upon are most specific. If no such method exists (e.g. since you have method(Base, Sub) and method(Sub, Base) but not method(Sub, Sub)), then the compilation fails.

Note that the actual choice of method depends on the dynamic type of the target object for instance methods, but not for the parameters. Your example would still work the same on the instance level.

You should be able to give the compiler a helping hand by casting or redeclaring the type of ss. If the declared type of the variable matches a signature exactly then everything is clear for the compiler and maintenance programmers as well. It doesn't matter if you then assign a more specific type as long as the declared type matches.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值