/* SimpleSubclasses/Main.java Main -- Simple class to get program going. Creates a few Ants and AntEaters, subclasses of Animal. Compile: javac Main.java Animal.java Ant.java AntEater.java Run: java Main Copy: cp /users/rlr/Courses/530/Src/SimpleSubclasses/*.java yourDir */ import java.util.*; // for misc java classes (eg ArrayList, Random) public class Main { public static void main ( String args[] ) { int numberOfAnts = 4; // create this many ants. int numberOfAntEaters = 4; // create this many anteaters Ant anAnt; // scratch var AntEater anAntEater; // define an ArrayLists for each type of object, and for both! ArrayList antList = new ArrayList (); ArrayList antEaterList = new ArrayList (); ArrayList animalList = new ArrayList (); // create a bunch of ants, adding them to antList and animalList System.out.printf( "\nCreate %d ants...", numberOfAnts ); for ( int i = 0; i < numberOfAnts; ++i ) { anAnt = new Ant(); antList.add( anAnt ); animalList.add( anAnt ); } // create a bunch of antEaters, adding them to antEaterList and animalList System.out.printf( "\n\nCreate %d antEaters...", numberOfAntEaters ); for ( int i = 0; i < numberOfAntEaters; ++i ) { anAntEater = new AntEater(); antEaterList.add( anAntEater ); animalList.add( anAntEater ); } // print the lists System.out.printf( "\n\nThe antList:\n" ); for ( Ant ant : antList ) ant.printSelf(); System.out.printf( "\n\nThe antEaterList:\n" ); for ( AntEater antEater : antEaterList ) antEater.printSelf(); System.out.printf( "\n\nThe animalList\n" ); for ( Animal animal : animalList ) animal.printSelf(); // tell them to move System.out.printf( "\n\nTell animals to move:\n" ); for ( Animal animal : animalList ) animal.move(); // tell them to do animal specific actions System.out.printf( "\n\nTell animals to sting or lick:\n" ); for ( int anum = 0; anum < animalList.size(); ++anum ) { Animal animal = animalList.get( anum ); if ( animal.getClass() == Ant.class ) { // its an Ant ((Ant) animal).sting(); // "cast" as Ant, to sting } else { // must be an AntEater ((AntEater) animal).lick(); // cast as AntEater, to lick } } System.out.printf( "\nAll done, ciao!\n\n" ); } }