java重载的规则_Java重载规则

重载与覆盖

正如您所指出的那样,选择正确的方法实现是在运行时完成的,现在要调用的方法的签名是在编译时决定的.

编译时的重载方法选择

07.12(07)中的Java Language Specification(JLS)详细解释了编译器选择正确的调用方法所遵循的过程.

在那里,您会注意到这是一个编译时任务. JLS在第15.12.2小节中说:

This step uses the name of the method and the types of the argument expressions

to locate methods that are both accessible and applicable

There may be more than one such method, in which case the most specific one is chosen.

通常,如果varargs方法与其他候选方法竞争,则它们是最后选择的方法,因为它们被认为不如接收相同参数类型的方法具体.

要验证此编译时的性质,您可以执行以下测试.

声明一个这样的类并编译它.

public class ChooseMethod {

public void doSomething(Number n){

System.out.println("Number");

}

}

声明第二个类,它调用第一个方法并编译它.

public class MethodChooser {

public static void main(String[] args) {

ChooseMethod m = new ChooseMethod();

m.doSomething(10);

}

}

如果调用main,则输出显示Number.

现在,向ChooseMethod类添加第二个更具体的重载方法,并重新编译它(但不要重新编译其他类).

public void doSomething(Integer i) {

System.out.println("Integer");

}

如果再次运行main,则输出仍为Number.

基本上,因为它是在编译时决定的.如果重新编译MethodChooser类(具有main的类),并再次运行该程序,则输出将为Integer.

因此,如果要强制选择其中一个重载方法,则参数类型必须与编译时参数的类型相对应,而不仅仅是在运行时.

在运行时覆盖方法选择

同样,方法的签名在编译时决定,但实际的实现是在运行时决定的.

声明一个这样的类并编译它.

public class ChooseMethodA {

public void doSomething(Number n){

System.out.println("Number A");

}

}

然后声明第二个扩展类并编译:

public class ChooseMethodB extends ChooseMethodA { }

在MethodChooser类中,您可以:

public class MethodChooser {

public static void main(String[] args) {

ChooseMethodA m = new ChooseMethodB();

m.doSomething(10);

}

}

如果你运行它,你得到输出数字A,这是好的,因为该方法尚未在ChooseMethodB中被覆盖,因此被调用的实现是ChooseMethodA的实现.

现在,在MethodChooserB中添加一个overriden方法:

public void doSomething(Number n){

System.out.println("Number B");

}

并重新编译这一个,并再次运行main方法.

现在,您获得输出数字B.

因此,在运行时选择了实现,而不需要重新编译MethodChooser类.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值