You can define a class for graphical objects like this:
object class \ "object" is the parent class selector draw ( x y graphical -- ) end-class graphical
This code defines a class graphical
with an
operation draw
. We can perform the operation
draw
on any graphical
object, e.g.:
100 100 t-rex draw
where t-rex
is a word (say, a constant) that produces a
graphical object.
How do we create a graphical object? With the present definitions,
we cannot create a useful graphical object. The class
graphical
describes graphical objects in general, but not
any concrete graphical object type (C++ users would call it an
abstract class); e.g., there is no method for the selector
draw
in the class graphical
.
For concrete graphical objects, we define child classes of the
class graphical
, e.g.:
graphical class \ "graphical" is the parent class cell% field circle-radius :noname ( x y circle -- ) circle-radius @ draw-circle ; overrides draw :noname ( n-radius circle -- ) circle-radius ! ; overrides construct end-class circle
Here we define a class circle
as a child of graphical
,
with field circle-radius
(which behaves just like a field
(see Structures); it defines (using overrides
) new methods
for the selectors draw
and construct
(construct
is
defined in object
, the parent class of graphical
).
Now we can create a circle on the heap (i.e.,
allocate
d memory) with:
50 circle heap-new constant my-circle
heap-new
invokes construct
, thus
initializing the field circle-radius
with 50. We can draw
this new circle at (100,100) with:
100 100 my-circle draw
Note: You can only invoke a selector if the object on the TOS
(the receiving object) belongs to the class where the selector was
defined or one of its descendents; e.g., you can invoke
draw
only for objects belonging to graphical
or its descendents (e.g., circle
). Immediately before
end-class
, the search order has to be the same as
immediately after class
.