简体   繁体   English

编译器根据什么标准选择重载方法之一

[英]On what criterion compiler chooses one of the overloaded method

What is the formal reason of prefering one to method to the other(by compiler)? 相对于另一种方法(通过编译器)优先使用一种方法的正式原因是什么? Why it chooses first one for bytes etc. I know that int can represent bytes, but float also. 为什么它为字节等选择第一个。我知道int可以表示字节,但也可以浮动。 Why is it so formally? 为什么这么正式?

public class MethodCurrier {

    public void setValue(int wrt){//naglowek
        System.out.println("Typ int "+ wrt);
    }
    public void setValue(float wrt){//naglowek
        System.out.println("Typ float "+ wrt);
    }
    public static void main(String[] args) {
        MethodCurrier currier = new MethodCurrier();
        currier.setValue(4);//int
        currier.setValue(2.3f);//float
        currier.setValue('c');//char
        currier.setValue((byte)4);

    }
}

The Java Language Specification defines this as follows: Java语言规范对此进行了如下定义

If more than one member method is both accessible and applicable to a method invocation, it is necessary to choose one to provide the descriptor for the run-time method dispatch. 如果多个成员方法都可访问并适用于方法调用,则必须选择一个为运行时方法调度提供描述符。 The Java programming language uses the rule that the most specific method is chosen. Java编程语言使用选择最具体方法的规则。

The informal intuition is that one method is more specific than another if any invocation handled by the first method could be passed on to the other one without a compile-time type error. 非正式的直觉是,如果第一个方法处理的任何调用都可以传递给另一个没有编译时类型错误的调用,那么一个方法比另一个方法更具体。

In your case, the int method is more specific than the float method, because an int can be implictly converted to a float , but not vice versa. 在您的情况下, int方法比float方法更具体,因为可以将int隐式转换为float ,反之亦然。

因为Java语言规范是这样说的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM