Friday, 22 April 2011

Arrays of Base class objects

As with arrays of primitive types, arrays of objects allow much more efficient methods of access. Note in this example that once the array of Animals has been structured, it can be used to store objects of any subclass of Animal. By making the method speak() abstract, it can be defined for each subclass and any usage will be polymorphic (ie. adapted to the appropriate object type at runtime). It now becomes very easy to rehearse the speak() method for each object by object indexing.


public class AnimalArray
{
  public static void main(String args[])
  Animal ref[] = new Animal[3]; // assign space for array
  Cow aCow = new Cow("Bossy");  // makes specific objects
  Dog aDog = new Dog("Rover");
  Snake aSnake = new Snake("Earnie");

  // now put them in an array
  ref[0] = aCow; ref[1] = aDog; ref[2] = aSnake;

  // now demo dynamic method binding
  for (int x=0;x<3;++x) { ref[x].speak(); }
}

No comments:

Post a Comment