View Single Post
  #28 (permalink)  
Old 01-23-2008, 11:42 PM
tim's Avatar
tim tim is offline
Senior Member
 
Join Date: Dec 2007
Location: South Africa
Posts: 334
tim is on a distinguished road
Adding polymorphism
Hello mcal

Lets add some classes to the show. Lets have the abstract class Animal and a few extensions of it:
Code:
public abstract class Animal(){ protected String sound; public Animal(){ sound = ""; } public void printSound(){ System.out.println(sound); } public abstract void createSound(); }
And the extensions:
Code:
public class Dog extends Animal{ public Dog(){ super(); } public void createSound(){ sound = "bark"; } }
Code:
public class Snake extends Animal{ public Snake(){ super(); } public void createSound(){ sound = "hisss"; } }
Let's create a vector of Animal instances.
Code:
Vector<Animal> animals = new Vector<Animal>(); Dog dog = new Dog(); Snake snake = new Snake(); dog.createSound(); snake.createSound(); animals.add(dog); animals.add(snake);
What all this code does is create a structure where we can define classes that inherit attributes and behavior from their parent. So, I've started with an abstract class Animal. An abstract class cannot be instanced. This makes sense, since we cannot create an Animal, unless we know what type of animal it is. The subclasses of Animal, Dog and Snake, are not abstract. The reason for this structure is that when you collect information, you want some way of handling all your data types will the minimum amount of work and code. Lets say that I want to print all the sounds that the animals make in my vector.
Code:
for (int i = 0; i < animals.size(); i++){ Animal animal = animals.get(i); animal.printSound(); }
Now, if I wanted to add a Cat class, I just have to extend the Animal class and make sure I implement the createSound() abstract method. I don't have to touch the for loop above. This makes it easy to extend your Java programs.

This is all very handy, but what do you do if you want to know what classes you are handling? So, mcal, are you still interested? Just ask if something is unclear.
__________________
If your ship has not come in yet then build a lighthouse.
Reply With Quote