Show
with line numbers
// Carnivore.java shows (in a somewhat gruesome way) why polymorphism
// is useful. In the for loop (at the bottom), without polymorphism
// what version of favoritePrey() should get invoked?
//
// Written 1/2009 by Wayne Pollock, Tampa Florida USA
abstract class Carnivore
{
String name;
public absract String favoritePrey();
// ...
}
class Lion extends Carnivore
{
public String favoritePrey()
{ ... }
// ...
}
class Tiger extends Carnivore
{
public String favoritePrey()
{ ... }
// ...
}
class VisitorInfo
{
// ...
public static void main ( String [] args )
{
// ...
List<Carnivore> animals = new List<Carnivore>();
animals.add( new Lion(...) );
animals.add( new Tiger(...) );
// ...
}
public showInfo( List<Carnivore> animals )
{
for ( Carnivore c : animals )
{
System.out.print( "Name: " + c.name );
System.out.println( ", Eats: " + c.favoritePrey() );
}
}
}