Method overload (double and float)

6

Having 2 methods with the same name, but the types are different ( double and float ), the amount of parameter is the same, which one will Java recognize first and why?     

asked by anonymous 12.05.2016 / 22:30

1 answer

4

Depends on what value is used in your call. If the value is a float or any other that is automatically converted to float , it will be the method that receives float , if the type of argument of the method call is a double , it will call the method whose parameter is a double .

There is no such thing which will be called first. Except the question from a wrong premise.

class Classe {
     void metodo(float x) {
        System.out.printf("Float %f\n", x);
    }
     void metodo(double x) {
        System.out.printf("Double %f\n", x);
    }
}

class Ideone {
    public static void main(String args[]) {
        Classe classe = new Classe();
        classe.metodo(1);
        classe.metodo(1.0);
        classe.metodo(1.0f);
    }
}

See running on ideone and CodingGround .

    
12.05.2016 / 22:39