18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Inheritance<br />

A truly object-oriented language must support inheritance, the capability of a class to reuse<br />

(inherit) methods and properties from another class. In the previous chapter, you learned how to<br />

define properties and methods of a class, but what if you want two classes to use the same methods?<br />

This is where inheritance comes in.<br />

Inheritance in Action<br />

The easiest way to describe inheritance is through a classic example, geometric shapes. There are<br />

really two types of shapes: ellipses (which are rounded) and polygons (which have a certain number<br />

of sides). Circles are a type of ellipse with one focus; triangles, rectangles, and pentagons are<br />

types of polygons with a different number of sides. A square is a type of rectangle with all sides<br />

equal. This describes a perfect inheritance relationship.<br />

In this example, Shape is the base class (the class to be inherited from) of Ellipse and Polygon. An<br />

Ellipse has one property called foci, indicating the number of foci the Ellipse has. Circle inherits<br />

from Ellipse, so Circle is a subclass of Ellipse and Ellipse is a superclass of Circle. Likewise, Triangle,<br />

Rectangle, and Pentagon are subclasses of Polygon and Polygon is a superclass to each of these<br />

shapes. Finally, Square inherits from Rectangle.<br />

The inheritance relationship is best explained through diagrams, which is where the Universal<br />

Modeling Language (UML) comes in. One of UML’s many purposes is to visually represent complex<br />

object relationships such as inheritance. Figure 4-1 is a UML diagram explaining the relationship<br />

of Shape to its subclasses:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!