11

I wrote this test code

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!";
        }


    }
}

The result was

float constructor called!

Why was the float constructor called rather than the double constructor? Is this part of the dynamic method lookup?

3
  • Were you expecting that it was cast to double? If so, why? Commented Feb 22, 2015 at 7:40
  • I was not expecting one way or the other. The question came up in class and I wrote the test to see but I don't know why the float takes precedence over the double. Commented Feb 22, 2015 at 7:45
  • 1
    There is no dynamic method lookup here. Commented Feb 22, 2015 at 9:01

2 Answers 2

20

ConstructorTest(float param) is the most specific method out of the two constructors, since a method with a double argument can accept any float value, but the opposite is not true.

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.

Sign up to request clarification or add additional context in comments.

Comments

3

I present JLS 5.3. Method Invocation Conversion and 5.1.2. Widening Primitive Conversion

19 specific conversions on primitive types are called the widening primitive conversions:

byte to short, int, long, float, or double

short to int, long, float, or double

char to int, long, float, or double

int to long, float, or double

long to float or double

float to double

Essentially floats are put in priority over doubles in method overloading when casting is done.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.