Created
March 11, 2011 11:21
-
-
Save frenchy64/865762 to your computer and use it in GitHub Desktop.
Discussion on dispatch method of Java
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 Dispatch { | |
public static void main(String[] args) { | |
// Start here | |
// Java uses single dispatch. | |
// | |
// Single dispatch is based on the runtime "type" of d, which is Dog. | |
Dog d = new Dog(); | |
// | |
// This matches the method makeNoise(Dog), because the runtime type is Dog | |
// | |
makeNoise(d); // should bark | |
// Here the runtime type is Animal, (but our instance type is Dog)... | |
Animal a = new Dog(); | |
// ... therefore makeNoise(Animal) is called because the runtime type is Animal. | |
makeNoise(a); | |
// This is probably not what we are after. | |
// Even though java knows it's a Dog, it doesn't help us here. | |
// | |
// We have to explicitely tell (remind) Java the runtime type by casting. | |
makeNoise( (Dog) a); // barks | |
// This usually means using instanceof at runtime to determine type | |
if (a instanceof Dog) | |
makeNoise( (Dog) a); | |
else if (a instanceof Duck) | |
makeNoise( (Duck) a); | |
// In the context of Sempedia | |
// ASType sdouble = SDouble(1.0); | |
// | |
// the runtime type is ASType, so to dispatch to SDouble we must cast... | |
// | |
// if (sdouble instanceof SResource) ... | |
// else if (sdouble instanceof SClass) .... | |
// ... | |
} | |
public static void makeNoise(Dog a) { | |
a.bark(); | |
} | |
public static void makeNoise(Duck a) { | |
a.quack(); | |
} | |
public static void makeNoise(Animal a) { | |
a.breath(); | |
} | |
/** | |
* Class for animals | |
**/ | |
static class Animal { | |
public void breath() { | |
System.out.println("Everything can breath"); | |
} | |
} | |
/** | |
* Class for dogs | |
**/ | |
static class Dog extends Animal { | |
public Dog() { } | |
public void bark() { | |
System.out.println("bark"); | |
} | |
} | |
/** | |
* Class for ducks | |
**/ | |
static class Duck extends Animal { | |
public void quack() { | |
System.out.println("quack"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment