Java calling overloaded methods -


consider code segment

class stockserver {      stockserver(string company, int shares,double currentprice, double cashonhand) {}     double buy(int numberofshares, double pricepershare) {          system.out.println("buy(int,double)");          return 3.0;    }      float buy(long numberofshares, double pricepershare) {              system.out.println("buy(long,double)");         return 3.0f;     }  } 

if execute lines of code,

stockserver = new stockserver("",2,2.0,2); byte b=5; a.buy(b,2); 

the results : buy(int,double)

i want know how compiler decide method execute?

if have overloaded methods, compiler figures out specific candidate using method signature. in case 2 signatures are

buy(int, double) 

and

buy(long, double). 

note return type not part of signature. calling method using buy(byte, int). since int more specific long, first method called. more specific means int smaller of 2 type contain byte.

however, compiler cannot figure out specific candidate time:

public static void foo(long a, double b) {     // body }  public static void foo(double a, long b) {     // body }  foo(3, 4); 

this code not compile, because not clear of methods meant.


Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -