Carnivore.java

Download Carnivore.java

 1: // Carnivore.java shows (in a somewhat gruesome way) why polymorphism
 2: // is useful.  In the for loop (at the bottom), without polymorphism
 3: // what version of favoritePrey() should get invoked?
 4: //
 5: // Written 1/2009 by Wayne Pollock, Tampa Florida USA
 6: 
 7: abstract class Carnivore
 8: {
 9:    String name;
10:    public absract String favoritePrey();
11:    // ...
12: }
13: 
14: class Lion extends Carnivore
15: {
16:    public String favoritePrey()
17:    { ... }
18:    // ...
19: }
20: 
21: class Tiger extends Carnivore
22: {
23:    public String favoritePrey()
24:    { ... }
25:    // ...
26: }
27: 
28: class VisitorInfo
29: {
30:    // ...
31:    public static void main ( String [] args )
32:    {
33:       // ...
34:       List<Carnivore> animals = new List<Carnivore>();
35:       animals.add( new Lion(...) );
36:       animals.add( new Tiger(...) );
37:       // ...
38:    }
39: 
40:    public showInfo( List<Carnivore> animals )
41:    {
42:       for ( Carnivore c : animals )
43:       {
44:          System.out.print( "Name: " + c.name );
45:          System.out.println( ", Eats: " + c.favoritePrey() );
46:       }
47:    }
48: }