↑

Main Page

# Creating the subclasses

In ECMAScript, the class can be written like this:

function Polygon(iSides) {

this.sides = iSides;

}

Polygon.prototype.getArea = function () {

return 0;

};

Note that the

Polygon

class isn’t specific enough to be used by itself;

getArea()

returns

0

because it is

just a placeholder for the subclasses to override.

Creating the subclasses

Now consider the

Triangle

class. A triangle has three sides, so this class has to override the

Polygon

class’s

sides

property and set it to

3

. The

getArea()

method also has to be overridden to use the area

formula for a triangle, which is

1

?

2

?

base

?

height. But how does the method get the values for base and

height? They must be entered specifically, and so you must create a

base

property and a

height

prop-

erty. The UML representation for

Triangle

is displayed in Figure 4-4.

Figure 4-4

This diagram shows only the new properties and overridden methods of

Triangle

. If

Triangle

doesn’t override

getArea()

, the method is not listed in the diagram. It would be considered as retained

from

Polygon

. The complete UML diagram showing the relationship between

Polygon

and

Triangle

(Figure 4-5) makes it a little bit clearer.

Figure 4-5

Triangle

base : integer

height: integer

getArea(): integer

Polygon

sides : integer

getArea(): integer

Triangle

base : integer

height: integer

getArea(): integer

112

Chapter 4

07_579088 ch04.qxd 3/28/05 11:36 AM Page 112

Free JavaScript Editor
Ajax Editor

©

↓