Polymorphism and its implementation in Java (Part II )

by Barry Nirmal

Go to Part I of this article.

Here is another example of polymorphism. Let us write an applet that performs animation. If you pass the parameter “RectangleAnimation” to it, it animates the applet region with a solid rectangle in blue. If you pass the parameter “CircleAnimation” to it, it animates it with a solid circle. The sleep time which is the time for which the thread sleeps before showing the next frame, is also passed to the applet as a parameter via HTML.

The following is the base class Animation:


import java.applet.Applet;

import java.awt.*;



abstract class Animation {

  protected Applet app;

  protected void init (Applet app) {

    this.app = app;

  }

  public abstract void advance ();

  public abstract void paintFrame(Graphics g);



} // end class



The following is the derived class RectangleAnimation:

import java. awt. *;

import java. applet. Applet;



public class RectangleAnimation extends Animation {

  private int cx = 0;

  private int cy = 0;



  public void advance (){

    Rectangle bounds = app. bounds();

    cx = (int) (Math. random() * 1000) % bounds.width;

    cy = (int) (Math. random() * 1000) % bounds.height;



} // end method



  public void paintFrame (Graphics g) {

    g. setColor (Color. blue);

    g. fillRect (cx, cy, 30, 30);

  }



} // end class

The following is the derived class CircleAnimation:

import java. awt. *;

import java. applet. Applet;



public class CircleAnimation extends Animation {



  public void advance (){

   (to be coded)



} // end method



  public void paintFrame (Graphics g) {

   (to be coded)

  }



} // end class



The following is the Applet class AnimationApplet:

import java. awt. *;

import java. applet. Applet;



public class AnimationApplet extends Applet  implements Runnable  {

  Thread xanimator;

  Animation  animation;

  long  sleepFor;



  public void init () {

    setBackground(Color.gray);

    String sleepTime =  getParameter ("sleepTime");

    if (sleepTime == null) sleepTime = "50";

    sleepFor = (long) Integer. parseInt(sleepTime);



    xanimator =  new Thread (this);

    String subclassName =  getParameter("animation");

    try {

      animation = (Animation) Class. forName(subclassName). newInstance() ;

    } catch (Exception e) {

       System. out.println("Exception at 100 = " + e) ;

    }

    animation. init (this);



} // end method



  public void start  ( ) {

  if (xanimator. isAlive ())

      xanimator. resume ();

    else

      xanimator. start();

  }



  public void stop  ( ) {

    xanimator. suspend ();

  }



  public void destroy   ( ) {

    xanimator. stop ();

  }



  public void run()  {

    while (true) {

      repaint ();

      try {

        Thread. sleep (sleepFor);

      } catch (Exception e) {

        }

      animation. advance ();

    }

  }  // end method



  public void paint (Graphics g) {

    animation. paintFrame (g);

  }



  public void update  (Graphics g) {

    paint(g);

  }



} // end class



The following is the HTML file for the applet:


<HTML>

<body>

<p>

<applet code=AnimationApplet.class height=100 width=300>

<param name=sleepTime value="1000">

<param name=animation value="RectangleAnimation">

</applet>

</body>

</HTML>

Important point to note in above design

Notice how in AnimationApplet class in the init() method we allocate an object of class Animation based on class name passed as parameter via the HTML file. If the class name isn’t currently found, the Java runtime will load the class over the net from the same place as the applet.

This makes this system flexible. It allows new Animation subclasses to be written and just dropped into the same directory that contains the applet. Web pages that want to make use of the new Animation class only need to pass the name of the new subclass rather than recompile the applet with the new subclass.

Why is polymorphism such a good thing?

Polymorphism helps make programs more flexible because at some future time, you can add another subclass to the Animation family, and pass its name via the HTML parameter and the new class will be used for animation. For example you can later add a Hexagon class, or a Pentagon class.

Can an abstract class implement a method?

Yes they can. In the example above, we find that Animation class is abstract but it implements method init().

Keep in mind some rules

(1) An abstract class is not required to have an abstract method in it. But any class that has an abstract method in it or that does not provide an implementation for any abstract methods in its superclass must be declared as an abstract class. This is why Animation class above is declared abstract.

How can you use the above concepts in your own design?

When you examine a real word system which you are trying to model via your object oriented design, look for situations which call for an abstract superclass and concrete subclasses. Then use the above techniques of design.

*** The End ***