Last active
December 28, 2015 04:09
-
-
Save rshepherd/7440781 to your computer and use it in GitHub Desktop.
Demonstration of subtype polymorphism
This file contains hidden or 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
import java.util.Random; | |
public class SubtypePolymorphism { | |
public static abstract class Animal { | |
public abstract String talk(); | |
public void write() { | |
System.out.println(this.talk()); | |
} | |
} | |
public static class Cat extends Animal { | |
public String talk() { | |
return "Meow!"; | |
} | |
} | |
public static class Dog extends Animal { | |
public String talk() { | |
return "Woof!"; | |
} | |
} | |
public static class UsingPolymorphism { | |
public static void main() { | |
Animal a = randomAnimal(); | |
a.write(); | |
} | |
} | |
public static class NotUsingPolymorphism { | |
public static void main() { | |
Animal a = randomAnimal(); | |
// 'Leaky abstraction'! maintenance pain! | |
if(a instanceof Dog) { | |
System.out.println("Woof!"); | |
} else if (a instanceof Cat) { | |
System.out.println("Meow!"); | |
} else { | |
// This is a big problem!!! | |
System.out.println("I don't know what you are."); | |
} | |
} | |
} | |
// See how much simpler the code is?. It also is | |
// future proof since any type that impelemements Animal | |
// will already be supported. Also, details about the behavior | |
// of animal implementations stays encapsulated in the implementations. | |
public static Animal randomAnimal() { | |
int r = new Random().nextInt(); | |
if(r % 2 == 0) { | |
return new Cat(); | |
} else { | |
return new Dog(); | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment