|
Re: OO - polymorphism - wtf??
| quote: | Originally posted by UglyDave
can some one explain what polymorphism is, as i'm having difficulty findin a good example on the net..
a class mate described it to me as being like this:
u have an alien, a lazer, and a ufo.
you tell them all to draw.
alien draws a pic of an alien.
lazer draws a lazer
ufo draws a ufo.
wtf?
please someone explain!
Dave |
That's actually a pretty good metaphor of what it is , here is a more formal explanation:
| quote: |
Polymorphism
Polymorphism is the ability of a class and possibly of different classes to have certain behavior identified by a common name but distinguished when invoked.
This is an extremely powerful feature of object-oriented programming. Consider two distinct classes in an inheritance hierarchy. Let us refer to their instances by their common class name and identify distinct behaviors by the same name. For example, let us ask all 'animals' of various species to 'draw' themselves. We use the common name (animal) and the common behavior (draw), but expect each instance to draw a diagram appropriate to its own species. We do not make separate drawing requests for each species. This enables us to introduce more species without introducing any more source code and to simplify our programming considerably.
Polymorphism means existence in many forms. This concept was first associated with programming by Strachey in 1967.
|
Source: http://cs.senecac.on.ca/~cszalwin/btp200/objec.html
Example from an ex prof of mine..:
code:
/** Explains polymorphism
JAC444 Lesson 4 Slide 11
@version 1.0, May 19, 2000
@author Jordan Anastasiade
*/
import java.util.*;
class Shape {
Shape(int i) {
System.out.println("\nShape constructor called");
}
void cleanup() {
System.out.println("Shape cleanup \n");
}
}
class Circle extends Shape {
Circle(int i) {
super(i);
System.out.println("\tDrawing a Circle \n");
}
void cleanup() {
System.out.println("\tErasing a Circle");
super.cleanup();
}
}
class Triangle extends Shape {
Triangle(int i) {
super(i);
System.out.println("\tDrawing a Triangle \n");
}
void cleanup() {
System.out.println("\tErasing a Triangle");
super.cleanup();
}
}
public class DrawSystem extends Shape {
private Circle c;
private Triangle t;
private Shape[] drawObjs;
DrawSystem(int nrObjs) {
super(nrObjs);
drawObjs = new Shape[nrObjs];
c = new Circle(1);
t = new Triangle(1);
drawObjs[0] = c;
drawObjs[1] = t;
System.out.println("DrawSystem constructor finishes.\n\n");
}
void cleanup() {
System.out.println("\n\nSystem.cleanup() begins");
for(int i = 0; i < drawObjs.length; i++)
drawObjs[i].cleanup();
super.cleanup();
}
public static void main(String[] args) {
DrawSystem x = new DrawSystem(2);
//drawing methods
x.cleanup();
}
}
Notice how the cleanup() is called and thanks to polymorphism, the corresponding cleanup from the derived objects are called.
___________________
[alk]
|