6 class — Object-oriented programming (classes)
This is an example of inheritance. class rotated coord is an extension of class coord.
In object-oriented programming, we would say this as “class rotated coord inherits
from class coord”. A class that inherits from another class is known as a “subclass”.
4. Next we defined our replacement and new functions. The definitions are
real scalar rotated_coord::angle()
{
return(super.angle() - theta)
}
void rotated_coord::new()
{
theta = 0
}
Concerning angle(), we stated that it is calculated by taking the result of super.angle()
and subtracting theta from it. super.angle() is how one refers to the parent’s definition of
a function. If you are unfamiliar with object-oriented programming, parent may seem like an
odd word in this context. We are inheriting concepts from coord to define rotated coord,
and in that sense, coord is the parent concept. Anyway, the new definition of an angle is
the old definition, minus theta, the angle of rotation.
new() is a special function and is given a special name in the sense that the name new() is
reserved. The new() function, if it exists, is a function that is called automatically whenever
a new instance of the class is created. Our new() function says that when a new instance
of a rotated coord is created, initialize the instance’s theta to 0.
Well, that seems like a good idea. But we did not have a new() function when we defined
our previous class, coord. Did we forget something? Maybe. When you do not specify a
new() function—when you do not specify how variables are to be initialized—they are
initialized in the usual Mata way: missing values. x and y will be initialized to contain
missing. Given our new() function for rotated coord, however, theta will be initialized
to 0.
new() is called a “constructor”, because it is used to construct, or initialize, the class when
a new instance of the class is created.
And that completes the definition of our two, related classes.
There are two ways to create instances of a coord or a rotated coord. One is mostly for interactive
use and the other for programming use.
If you interactively type a=coord() (note the parentheses), you will create a coord and store it in
a. If you interactively type b=rotated coord(), you will create a rotated coord and store it
in b. In the first example, typing b=rotated coord() is exactly what we chose to do:
: b = rotated_coord()
Recall that a rotated coord contains an x, y, and theta. At this stage, x and y equal missing,
and theta is 0. In the example, we set b’s x and y values to 1, and then asked for the resulting
angle():
: b.x = b.y = 1
: b.angle()
45