java - 为什么在调用构造函数时将 int 隐式转换为 float 而不是 double?

标签 java constructor

我写了这段测试代码

public class ConstructorTestApplication {

    private static String result;


    public static void main(String[] args) {

        ConstructorTest test1 = new ConstructorTest(0);
        System.out.println(result);
    }

    private static class ConstructorTest {

        public ConstructorTest(double param){
            result = "double constructor called!";
        }
        public ConstructorTest(float param) {
            result = "float constructor called!";
        }


    }
}

结果是

float constructor called!

为什么调用 float 构造函数而不是 double 构造函数?这是动态方法查找的一部分吗?

最佳答案

ConstructorTest(float param) 是两个构造函数中最具体的方法,因为带有 double 参数的方法可以接受任何 float 值,但反之则不然。

JLS 15.12.2.5 :

15.12.2.5. Choosing the Most Specific Method

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.

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.

关于java - 为什么在调用构造函数时将 int 隐式转换为 float 而不是 double?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28655610/

相关文章:

java - Android 更好地实现了用于导航的 fragment

java - 如何为 Firebase 数据库异常添加内置类的无参数构造函数?

c++如何将名称传递给基类的构造函数

Java编译器错误: "cannot find symbol constructor .."?

c++ - 通过 C++ 中的模板参数传递类构造函数

c++ - 如何在构造函数中初始化数组?

java - 适用于 Java 7 的简单代码指标独立 Maven 插件

java - 如何为 Async Spring 使用多个 threadPoolExecutor

java - Java 7 和 Java 8 可以在 OSX 上共存吗

java - 如何使用包含数组的对象?