Here's how Webopedia.com defines polymorphism:
"Generally, the ability to appear in many forms. In object-oriented programming, polymorphism refers to a programming language's ability to process objects differently depending on their data type or class."
In truly object-oriented languages, polymorphism is usually tied to class-based inheritance. That is, you define a class hierarchy with abstract classes at the top and concrete implementations further down. In the abstract class, you define a method that subclasses must implement or override. The implementation of that method varies depending on the needs of the subclass.
The classic example involves shapes. For example, the formula to find the area of a rectangle is completely different from the formula to find the area of a circle. You might define an abstract class called Shape that includes a method called findArea() that subclasses must implement. You'd then define classes such as Rectangle and Circle that inherit from Shape. In each of the subclasses, you'd implement the findArea() method so that it returns the correct results based on the type of shape. The end result is that you can just call the findArea() method on any shape without worrying about how the method does its work.
Setting up the HTML and CSS
Open your favorite text editor and enter or copy the HTML code and CSS styles for this project:
Write the Script
font: 10pt Verdana,sans-serif;
In any object-oriented system, it's a good idea to create a hierarchy of objects that describes the system. This implementation includes a tree object that holds a collection of branch objects. Each branch object, in turn, holds a collection of children that can be either branches or leaf objects. In addition, each object type implements a polymorphic write() method that acts appropriately for that object's needs. That is, a tree object has a write()
method whose behavior differs from a branch object's write()
methodwhich is different from the leaf object's write()
method. The tree and branch objects also expose add()
methods that lets you add children to their respective collections.
Add a script block to the head of the document that creates the Image objects and functions necessary to achieve the effect of expanding and collapsing the branches of the tree, displaying or hiding the child items for any branch, and swapping the open or closed folder image as the branches exapand or collapse:
var openImg = new Image();
openImg.src = "open.gif";
var closedImg = new Image();
closedImg.src = "closed.gif";
var objBranch =
swapFolder('I' + branch);
objImg = document.getElementById(img);
objImg.src = openImg.src;
objImg.src = closedImg.src;
The preceding script sets up the image objects necessary to show the user that a folder is either open or closed. The showBranch()