Instantly share code, notes, and snippets.

Embed
What would you like to do?
Pet PolyMorphism Example
// Polymorphism Example
// A.C. Silvestri
// Java Programming
// 02/26/18
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 Pet();
break;
case 1:
case 2:
pets[i] = new Dog();
break;
case 4:
pets[i] = new Cat();
break;
default:
pets[i] = new BigBird();
pets[i].method(new BigBird());
break;
}
}
for (int i = 0; i < pets.length; i++) {
System.out.println("I am a " + pets[i].whatAmI() + " and I " + pets[i].speak());
}
}
}
class Pet {
String whatAmI() {
return "Pet";
}
String speak() {
return "Don't know how to speak";
}
void method(Pet b) {
System.out.println("Pet.Method");
}
void method(Bird b) {
System.out.println("Pet.Method.Bird");
}
}
class Dog extends Pet {
String whatAmI() {
return "Dog";
}
String speak() {
return "Woof";
}
}
class Cat extends Pet {
String whatAmI() {
return "Cat";
}
String speak() {
return "Meow";
}
}
class Bird extends Pet {
String whatAmI() {
return "Bird";
}
String speak() {
return "Cheep";
}
void method(Object o) {
System.out.println("Bird.Method");
}
}
class BigBird extends Bird {
void method(Bird o) {
System.out.println("BigBird.Method");
}
void method(Pet p) {
System.out.println("BigBird.PetMethod");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment