Java Casting in Method Overloading -


i have methods overloading such as:

 public int sum1(int a, int b) {     int c= a+b;      system.out.println("the method1");     return c;  } public float sum1(int a, float b) {     float c=  a+b;     system.out.println("the method2");     return c;  } public double sum1(float a, float b) {     double c=  (double) a+b;     system.out.println("the method3");     return c;  } 

from main method, suppose have

 double x=10.10f;  double y=10.20f;  

the apparent type x , y double, actual type float. when call

system.out.println(" output :"+cc.sum1(x,y));  

the error in compile-time.

the method sum1(int, int) in type class not applicable arguments double, double).  

where should go sum1 (i.e. method3) casting double float

tl;dr version of answer:

  • variables of primitive types never have different type @ execution-time compile-time. (a double double, never float, etc.)
  • overload resolution (picking method signature used) performed using compile-time types of expressions
  • method implementation of picked signature performed using execution-time type of target of method call

the apparent type x , y double, actual type float

no, it's not. you've got conversion assigned float literals double values. actual values double.

primitives don't work objects - there's no idea of int value still being int inside double variable, example.

it's simpler take example integer types. suppose have:

byte b = 100; int x = b; 

the value of x 32-bit integer representing value 100. doesn't "know" assigned byte value... there happened conversion byte int @ point of assignment.

compare reference types:

string x = "hello"; object y = x; 

here, value of y is reference string object. type information preserved precisely because there's whole object can contain it, , because value of variable reference. (the bits don't need change part of assignment - in simple vm @ least, they'll exact same bits in x , y, because they're referring same object.)

even in case, however, overload resolution occurs based on compile-time type of arguments, not actual values @ execution time. way execution-time type of variable gets involved overriding based on target of method call. if have:

foo f = new x(); foo g = new y(); foo h = new z();  f.somemethod(g, h); 

... compiler method in foo has 2 foo parameters (or object or other superclasses/interfaces) - actual types of objects involved irrelevant. @ execution time, however, if method has been overridden in x, override called due execution-time type of object f's value refers to.


Comments

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -