Last active
March 19, 2016 18:33
-
-
Save benjholla/8011fd547efa1286ce0d to your computer and use it in GitHub Desktop.
A small Java program demonstrating a dynamic dispatch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class DynamicDispatchExample { | |
public static void main(String[] args){ | |
A b1 = new B(); | |
A c1 = new C(); | |
A b2 = b1; | |
A c2 = c1; | |
// what will get printed? | |
b2.print(c2); | |
} | |
public static class A extends Object { | |
public void print(A object) { | |
System.out.println("An instance of " + object.getClass().getSimpleName() | |
+ " was passed to A's print(A object)"); | |
} | |
} | |
public static class B extends A { | |
public void print(A object) { | |
System.out.println("An instance of " + object.getClass().getSimpleName() | |
+ " was passed to B's print(A object)"); | |
} | |
} | |
public static class C extends B { | |
public void print(A object) { | |
System.out.println("An instance of " + object.getClass().getSimpleName() | |
+ " was passed to C's print(A object)"); | |
} | |
} | |
public static class D extends A { | |
public void print(A object) { | |
System.out.println("An instance of " + object.getClass().getSimpleName() | |
+ " was passed to D's print(A object)"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment