java - Use of overloading vs overriding, compile time vs run time -
effective:the choice of overloading invoke made @ compile time. example:
class parentsecond{ public int getdouble(int x){ return x*2;} } class second extends parentsecond{ public int getdouble(int x){ return x*3;} } class third{ public static void calloverload(parentsecond s){ system.out.println(s.getdouble(4)); } public static void calloverload(second s){ system.out.println(s.getdouble(4)); } public static void main(string[] args){ third t=new third(); parentsecond s=new second(); t.calloverload(s); } } answer 12. , behaviour same instance method overloaded method too.
so in either case ,the decision of overloaded method invoked made @ run-time rather compile time(its 'second's' getdouble invoked).
so there qualifications particular item in 'effective java' did not get.
please clarify meant 'resolving overloading @ compile-time'.
how above different this:
.... class fourth{ public static string getcollection(set<?> s){ return "set"; } public static string getcollection(collection<?> c){ return "collection"; } public string geticollection(set<?> s){ return "set"; } public string geticollection(collection<?> c){ return "collection"; } public static void main(string[] args){ collection<string> c=new hashset<string>(); system.out.println(fourth.getcollection(c)); fourth f=new fourth(); system.out.println(f.geticollection(c)); ... this answer in case 'collection' rather actual run-time type.
the declared type of s parentsecond when compiler runs through code, assign method takes parentsecond argument
public static void calloverload(parentsecond s)... however, overriding different subject. actual type of instance s second , second's getdouble method executed. case of polymorphism. in java, polymorphism accomplished through late-binding.
to quote this answer:
the jls states in §8.4.9 overloading:
- 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).
the argument s , compile time type parentsecond. run time type second.
edit answer addition question, see point 1 above. nothing needs evaluated @ run time. compiler uses compile time type, collection, in both calls.
Comments
Post a Comment