Using Properties and Methods:
Our classes so far have been pretty simple, and used mainly to introduce the
syntax for creating classes, objects, properties, and procedures.
However, the real power of object oriented programming is using properties and
methods together.
There is an important concept we must understand before we can use properties
and methods together. When you define a property or a method, you define
it for the overall class and not for the individual object. However,
when you use a property or method, you use it with a particular object,
not a class.
This is where the problem lies. Suppose we want to create a class called
Box. The Box class will have a Size property. We also want to create a method
that draws the Box. The Draw method will use the Size property, to draw the Box
on the screen. If you recall that with properties and methods, we need an
object before we can give properties a value or run methods. However, with
a class we don't know what objects will be created, so how can we use the Size
property?
Here is where the thisclass concept comes in. Thisclass
refers to the current object, and you can use it with both properties and
methods to derefence an object without knowing what the actual object is. So if
you look back at the two previous classes we created: House and Car. Then
we could refer to the current house as thishouse or the current
car as thiscar. You are probably thinking that this is about as
clear as mud, so I think an example would help.
Let's create our Box class.
? defineclass "box
Next let's define our Size property
? defineproperty "box "size
Now let's define our Draw method. Our Draw method will use the Size of the
object to draw the box. This is where we will use the thisclass,
in this case since our class is called Box, we will use thisbox.
? definemethod "box "Draw [[] [repeat 4 [ fd thisbox.size rt 90]]
Now let's test our new class out by creating a few boxes, and setting their
size.
? newbox "box1
? newbox "box2
? newbox "box3
? newbox "box4
? box1.setsize 50
? box2.setsize 100
? box3.setsize 150
? box4.setsize 200
? box1.draw
draws box 50
? box2.draw
draws box 100
? box3.draw
draws box 150
? box4.draw
draws box 200
In the next section we will look at creating Constructors and Destructors .
|