Tuesday, May 11, 2010

Parallel class hierarchies with Java Generic


import java.util.ArrayList;
import java.util.Collection;

/*
 * Super class for Habitat hierarchy 
 */
public abstract class Habitat <A extends Animal> {
 
 /*
  * A generic collection that can hold Animal 
  * or any subclass of animal 
  */
 Collection<A> collection = new ArrayList<A>();
 
 /*
  * add an Inhabitant to the collection.
  * should be overridden by subclass
  */
  public abstract  void addInhabitant( A animal);
}
/*
 * Aquarium class inherit the collection from 
 * Habitat superclass. But limit the collection 
 * to Fish type. 
 */
public class Aquarium extends Habitat <Fish> 
{
 
 /*
  * (non-Javadoc)
  * @see Habitat#addInhabitant(Animal)
  */
 @Override
 public void addInhabitant( Fish fish) { 
  collection.add(fish);
     System.out.println(Aquarium.class); 
   } 
}

/*
 * Super class for Animal hierarchy
 */
public abstract class Animal {

}
public class Fish extends Animal {

}
public class Test {

 /**
  * @param args
  */
 public static void main(String[] args) {
  Animal animal = new Fish();
  Fish fish = new Fish();
  //new Aquarium().addInhabitant(Animal); -- would cause compiler error
  new Aquarium().addInhabitant(fish);
 }

}

1 comment:

  1. Or if you'd like to read the original work:

    http://www.angelikalanger.com/GenericsFAQ/FAQSections/ProgrammingIdioms.html#FAQ201A

    ReplyDelete