/**
Polymorphism.java */
/*
Example taken from: Michael Daconta et.
al., Java 1.2 and JavaScript for C and C++ Programmers, John Wiley & Sons,
Inc., 1998. ISBN: 0-471-18359-8 */
package
jwiley.chp3;
import
java.util.Random;
/**
abstract class that represents a "generic" animal. */
abstract
class Animal
{
public abstract void iAmA();
public void speak()
{ System.out.println("Burp!"); }
}
/**
specific type of animal. */
class
Bird extends Animal
{
public void iAmA()
{
System.out.println("I am a Bird."); }
public void speak()
{ System.out.println("Cheep!");
}
}
/**
specific type of animal. */
class
Dog extends Animal
{
public void iAmA()
{ System.out.println("I am a
Dog."); }
public void speak()
{ System.out.println("Bark!"); }
}
/**
specific type of animal. */
class
Snake extends Animal
{
public void iAmA()
{ System.out.println("I am a
Snake."); }
public void speak()
{ System.out.println("Ssssss!");
}
}
/**
specific type of animal. */
class
human extends Animal
{
public void iAmA()
{ System.out.println("I am a
human."); }
}
/**
Class to demonstrate polymorphism. */
public
class Polymorphism
{
static Random dice = new Random();
/** method to randomly catch an animal for
our "zoo". */
static Animal catchAnimal()
{
int iRoll = Math.abs(dice.nextInt() %
3);
switch (iRoll)
{
case 0:
return new Bird();
case 1:
return new Dog();
case 2:
return new Snake();
}
return null;
}
/** main method to invoke from JVM.
We catch a bunch of animals, put them
in
the zoo (an array) and let them speak!
*/
public static void main(String args[])
{
Animal zoo[] = new Animal[6];
for (int i=0; i < 6; i++)
zoo[i] = catchAnimal();
for (int i=0; i < 6; i++)
{
zoo[i].iAmA();
zoo[i].speak();
}
human aHuman = new human();
aHuman.iAmA();
aHuman.speak();
}
}