This code was written to solve an excercise in the book "Objects First With Java"
/******************************************************************************/ /* */ /* FILE: Animal.java */ /* */ /* Base class for all the animals */ /* ============================== */ /* */ /* V1.00 19-NOV-2011 Te http://www.heimetli.ch */ /* */ /******************************************************************************/import java.lang.reflect.* ;
/** * This code demonstrates how to create child classes in a base class. */public class Animal {
/** * This method creates new instances of the subclasses. * * It uses reflection to get the constuctor of the child class and * to call this constructor. * * You probably need a fairly recent version of java. The calls to * reflection were more complicated in earlier versions ... */public void breed() { try { Constructor<? extends Animal> constructor = getClass().getDeclaredConstructor( boolean.class, Field.class, Position.class ) ; Animal animal = constructor.newInstance( true, new Field(), new Position() ) ; } catch( Exception e ) { System.out.println( e ) ; } } }
/** * An extremely simple subclass, having only a constructor */public class Hare extends Animal {
/** * This constructor will be called by the superclass */public Hare( boolean flag, Field field, Position position ) { System.out.println( "Hare constructor: " + flag ) ; } }
/** * Another extremely simple subclass, to prove that it works with all subclasses. */public class Fox extends Animal {
/** * This constructor will be called by the superclass */public Fox( boolean flag, Field field, Position position ) { System.out.println( "Fox constructor: " + flag ) ; } }
public class Field
{
}
public class Position
{
}
/** * Main class to prove that the code really works. */public class Main {
/** * Creates two different instances of subclasses and * calls the breed method in the base class to * create new instances of the same type. */public static void main( String args[] ) { Hare h = new Hare( false, new Field(), new Position() ) ; Fox f = new Fox( false, new Field(), new Position() ) ; h.breed() ; f.breed() ; } }