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.

Circle(radius):={
    .radius=radius;
    .area=Circle_area;
}
Circle_area(none):=PI*.radius^2

You can use this constructor to create a new object as follows:

var shape=new Circle(5);

Once the object is defined, you can calculate its area as

shape.area()

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:

var shapes=[
    new Circle(5),
    new Circle(6),
    new Square(4),
    new Triangle(3,4)
];

Finally, calculate the total area of all shapes by having each object call its own area method:

var total=sum(
    each(obj.area(),obj,shapes)
);

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.