What is this weird dynamic method dispatch behavior inside a static method in Java -


the utility method in below example illustration purposes only.

in example below, instance method invocation dispatched reference type not run-time object.

import java.sql.timestamp; import java.util.date; public class dynamicmethoddispatchex {      public static void main(string[] args) {         timestamp = new timestamp(system.currenttimemillis());         timestamp beforenow = new timestamp(now.gettime() - 1);          system.out.println("finding newest in " + + " , " + beforenow);         system.out.println("attempt 1: " + staticfindnewer(beforenow, now));         system.out.println("attempt 2: " + staticfindnewer(now, beforenow));      }      public static date staticfindnewer(date one, date two) {         if (one.after(two)) {             return one;         } else {             return two;         }     }  } 

the below output got

finding newest in 2016-08-23 17:56:36.375 , 2016-08-23 17:56:36.374 attempt 1: 2016-08-23 17:56:36.375 attempt 2: 2016-08-23 17:56:36.374 // <--- 

after investigation, found out java.util.date.after(date) being invoked in staticfindnewer() , discrepancy in attempt 1 , 2 , due precision loss date's methods being used.

however, i'm puzzled dynamic dispatch. i expected timestamp#after(timestamp) invoked date#after(date) getting invoked. thought instance-method dispatch based on runtime object. missing silly (most probably)?

i expected timestamp#after(timestamp) invoked date#after(date) getting invoked. thought instance-method dispatch based on runtime object.

dynamic dispatch happens on invoked object, not on arguments.

so call go timestamp#after(date) (because compile-time type of argument date, , runtime type of callee timestamp).

unfortunately, timestamp not override method, defaults date#after(date) (which not work here).

so have make sure call timestamp#after(timestamp) directly, or use date#compareto(date) method instead, implemented (and overridden in timestamp).


Comments

Popular posts from this blog

mysql - Dreamhost PyCharm Django Python 3 Launching a Site -

java - Sending SMS with SMSLib and Web Services -

java - How to resolve The method toString() in the type Object is not applicable for the arguments (InputStream) -