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/2019 by Wayne Pollock, Tampa Florida USA
 6: 
 7: import java.util.*;
 8: 
 9: abstract public class Carnivore {
10:     String name;
11:     abstract public String favoritePrey ();
12:     public Carnivore ( String name ) {
13:         this.name = name;
14:     }
15:     // ...
16: }
17: 
18: class Lion extends Carnivore {
19:     Lion ( String name ) {
20:         super(name);
21:     }
22: 
23:     public String favoritePrey () {
24:         // ...
25:         return "water buffalo";
26:     }
27: }
28: 
29: class Tiger extends Carnivore {
30:     Tiger ( String name ) {
31:         super(name);
32:     }
33: 
34:     public String favoritePrey () {
35:         // ...
36:         return "deer";
37:     }
38: }
39: 
40: class CarnivoreDemo {
41:     // ...
42:     public static void main ( String [] args ) {
43:         // ...
44:         List<Carnivore> animals = new ArrayList<>();
45:         animals.add( new Lion("Leo") );
46:         animals.add( new Tiger("Tony") );
47:         showInfo (animals);
48:     }
49: 
50:     public static void showInfo( List<Carnivore> animals ) {
51:         // Polymorphism at work:
52:         for ( Carnivore c : animals ) {
53:             System.out.print( "Name: " + c.name );
54:             System.out.println( ", Eats: " + c.favoritePrey() );
55:         }
56:     }
57: }