-
-
Save bytecodeman/cb239dd4dd0a904de6aba605cd129082 to your computer and use it in GitHub Desktop.
Pet PolyMorphism Example
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
// Polymorphism Example | |
// A.C. Silvestri | |
// Java Programming | |
// 07/20/2020 | |
public class PetPolyMorphism { | |
public static void main(String[] args) | |
{ | |
Pet pets[] = new Pet[10]; | |
for (int i = 0; i < pets.length; i++) { | |
switch ((int)(Math.random() * 10)) { | |
case 0: | |
pets[i] = new BigBird(); | |
break; | |
case 1: | |
case 2: | |
pets[i] = new Dog(); | |
break; | |
case 4: | |
pets[i] = new Cat(); | |
break; | |
case 5: | |
pets[i] = new Snake(); | |
break; | |
default: | |
pets[i] = new Bird(); | |
break; | |
} | |
} | |
for (int i = 0; i < pets.length; i++) { | |
pets[i].method(new BigBird()); | |
// System.out.println("I am a " + pets[i].whatAmI() + " and I " + pets[i].speak()); | |
// if (pets[i] instanceof Dog) { | |
// Dog d = (Dog)pets[i]; | |
// d.bark(); | |
// } | |
} | |
} | |
} | |
abstract class Pet { | |
abstract String whatAmI(); | |
abstract String speak(); | |
void method(Pet b) { | |
System.out.println("Pet.PetMethod"); | |
} | |
void method(Bird b) { | |
System.out.println("Pet.BirdMethod"); | |
} | |
} | |
class Snake extends Pet { | |
String whatAmI() { | |
return "Snake"; | |
} | |
String speak() { | |
return "Hiss"; | |
} | |
} | |
class Dog extends Pet { | |
String whatAmI() { | |
return "Dog"; | |
} | |
String speak() { | |
return "Woof"; | |
} | |
void bark() { | |
System.out.println("Barking Dog"); | |
} | |
} | |
class Cat extends Pet { | |
String whatAmI() { | |
return "Cat"; | |
} | |
String speak() { | |
return "Meow"; | |
} | |
} | |
class Bird extends Pet { | |
String whatAmI() { | |
return "Bird"; | |
} | |
String speak() { | |
return "Tweet"; | |
} | |
void method(Object o) { | |
System.out.println("Bird.Method"); | |
} | |
} | |
class BigBird extends Bird { | |
void method(Pet p) { | |
System.out.println("BigBird.PetMethod"); | |
} | |
void method(Bird o) { | |
System.out.println("BigBird.BirdMethod"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment