AS1 OOP: Inheritance
         by senocular  

Polymorphism
The idea behind polymorphism is that you are able to define methods for classes that are able to behave according to the needs of the instances created. This is especially the case for derived objects – each having their own versions of a similar method which performs the actions needed specific to that class.

Think about a basic shape super class. Two new subclasses can be derived from that, a circle and a square class. These classes can then both have a getCircumference method to retrieve the circumference of the shape though the definition for getCircumference will differ for each.
 

// Shape super class
Shape = function(x,y){
this.x = x;
this.y = y;
};
// Circle subclass
Circle = function(radius){
this.radius = radius;
};
// establish inheritance
Circle.prototype = new Shape();
// define unique getCircumference
Circle.prototype.getCircumference = function(){
return Math.PI*2*this.radius;
};
// Square subclass
Square = function(size){
this.size = size;
};
 
// establish inheritance
Square.prototype = new Shape();
// define unique getCircumference
Square.prototype.getCircumference = function(){
return 4*this.size;
};

 
// create some shapes
shapeA = new Circle(10);
shapeB = new Square(10);

 
trace(shapeA.getCircumference()); // traces 62.8318530717959
trace(shapeB.getCircumference()); // traces 40

Different methods they may be, but the fact remains, if you need to get the circumference of a shape, you still can, no matter what kind of shape you have.

 

Prev Page
 



SUPPORTERS:

kirupa.com's fast and reliable hosting provided by Media Temple.