Home Search Contact us About us
Title How Polymorphism works.
Summary A simple example of Polymorphism using extends. As usual this is done using the animal sound example.
Contributor John McTainsh
Published 25-Oct-2000
Last updated 25-Oct-2000
Page rating   100% for 2 votes Useless Brilliant

Description.

Polymorphism simply means creating an object with different forms. This is useful when modeling real world items in software. For example a car is a basic object but it can have many forms such as "Toyota", "Ford" and "Lada".

How to use it.

The following code demonstrates this by creating a base object, CAnimal as follows;
//This is an abstract (base) class that all the amimals must support
abstract class CAnimal
{
    public abstract void WhatAreYou();
    public void Speak()
    {
        System.out.print( "Quite" );
    }
}
Note CAnimal uses the keyword abstract to indicating this is a base class and cannot use to create an object directly. The WhatAreYou(); has not body and MUST be declared in all classes that are derived from it. The classes below are derived from the CAnimal class.
//This snake overides name and sound
class CSnake extends CAnimal
{
    public void WhatAreYou()
    {
        System.out.print( "Snake" );
    }
    public void Speak()
    {
        System.out.print( "Sssssss" );
    }
}

//Monkey overides name but uses the default sound
class CMonkey extends CAnimal
{
    public void WhatAreYou()
    {
        System.out.print( "Monkey" );
    }
}
See how CSnake overides the Speak() method also. Now lets put it all together.
///////////////////////////////////////////////////////////////////////////////
// Program demonstrates a single class having diferent forms.
public class Polymorph
{
    // The main entry point for the application. 
    // @param args Array of parameters passed to the application
    public static void main (String[] args)
    {
        System.out.println( "Starting Polymorph application" );
        //Initialize array of zoo animals
        CAnimal zoo[] = new CAnimal[2];
        zoo[0] = new CMonkey();
        zoo[1] = new CSnake();
        //Output results
        for( int n = 0; n < zoo.length; n ++ )
        {
            zoo[n].WhatAreYou();
            System.out.print( " says " );
            zoo[n].Speak();
            System.out.println( "." );
        }
        System.out.println( "Terminating Polymorph application!" );
    }
}
The above code will give the following output. Starting Polymorph application
Monkey says Quite.
Snake says Sssssss.
Terminating Polymorph application!
Comments Date
Home Search Contact us About us