Shape Object Example
The code below creates a constructor for a Circle object. The constructor accepts one argument (the circle radius) as input and assigns this value to an internal property. The object constructor also defines a method that calculates the area of the circle.
You can use this constructor to create a new object as follows:
Once the object is defined, you can calculate its area as
Now, expand the example by creating Square and Triangle object constructors as well. Just as in the Circle object, each new object has a method named area that calculates the shape's area.
Square(height):={
.height=height;
.area=Square_area;
}
Square_area(none):=.height^2
Triangle(height,width):={
.height=height;
.width=width;
.area=Triangle_area;
}
Triangle_area(none):=1/2*.height*.width
Now you can create a list of different shapes with code like this:
Finally, calculate the total area of all shapes by having each object call its own area method:
Because each object has its own area method, you do not need to be concerned about matching each object with the appropriate area function. Instead, each object knows how to calculate its own area.
Objects let you combine functions that work on data with the data itself. This can greatly simplify building and maintaining some applications.
See About Methods.