java - Overloading or a normal method -
this question has answer here:
i gonna put question have clear idea overloading concept in java . per understanding while method resolution in overloading compiler method signature should have same method name , different argument types . if return type different ??
class test{ public void m1(int i) { system.out.println(" int arg"); } public int m1(string s) { system.out.println("string-arg"); return (5+10); } public static void main (string[] args) throws java.lang.exception { test t = new test(); t.m1(5); int = t.m1("ani"); system.out.println(i); }}
the above program running . doubt here , method m1() overloaded ?? has different return type . please make clear. in advance
in java methods identified name , arguments' classes , amount. return type doesn't identify method. reason following code illegal:
public void m1(string i) { system.out.println(" int arg"); } public int m1(string s) { system.out.println("string-arg"); return (5+10); }
if 2 methods of class (whether both declared in same class, or both inherited class, or 1 declared , 1 inherited) have same name signatures not override-equivalent, method name said overloaded. (...) when method invoked (§15.12), number of actual arguments (and explicit type arguments) , compile-time types of arguments used, @ compile time, determine signature of method invoked (§15.12.2). if method invoked instance method, actual method invoked determined @ run time, using dynamic method lookup (§15.12.4)
summarizing, 2 methods same name can return different types, it's not being taken account when deciding method call. jvm first decides method call , later checks if return type of method can assigned variable.
example (try avoid such constructions):
public int pingpong(int i) { return i; } public string pingpong(string s) { return s; } public boolean pingpong(boolean b) { return b; }
Comments
Post a Comment