/* * Example of dynamic method dispatch in Java. * The oputput of this program is: AA: AA BB: BB CC: CC bb cast to AA: BB cc cast to AA: CC Had java used static method dispatch the output would be AA: AA BB: BB CC: CC bb cast to AA: AA cc cast to AA: AA * @author gtowell *created: Sep 26. 2021 */ public class DMD { // a class private class AA { @Override public String toString() { return this.getClass().getCanonicalName(); } } // another class, inherits from first private class BB extends AA { /** * @Override public String toString() { return "BB"; } **/ } // another class, inherits from first and second private class CC extends AA { /** * @Override public String toString() { return "CC"; } **/ } public static void main(String[] args) { new DMD().doWork(); } public void doWork() { AA aa = new AA(); BB bb = new BB(); CC cc = new CC(); System.out.println("Just calling the toString methods of each inner class"); System.out.println("AA: " + aa); System.out.println("BB: " + bb); System.out.println("CC: " + cc); // upcat each of bb and cc to AA AA caa = (AA) cc; AA baa = (AA) bb; System.out.println( "Call toStirng on instanceof classes after upcasting -- they still use the toStirng from their created type"); System.out.println("bb cast to AA: " + baa); System.out.println("cc cast to AA: " + caa); } }