Remember that we can tell the editor to begin a new namespace with )ed ⍟myns
? We can begin editing a new class with )ed ○myclass
.
Of course, that doesn't work with the chat bot or on TIO or TryAPL.
We could also create a new empty namespace with ⎕NS
. We can't do that with classes as they need some meta-information. However, we can use ⎕FIX
with a script to create a class. That's hard to read though, so I'll link to TIO instead.
Fundamental to a class it that it restricts which of its members can be "seen" from the outside.
By default fields (i.e. variables) and methods (i.e. functions) are "private", but we can make them "public" so that they can be seen.
This is convenient to implement black-box things and create layers of abstraction (for those that like such).
Another feature of fields and methods is whether they are "shared" among all the instances, or whether a separate method/field belongs to each instance. By default, they belong to the instances.
An instance is a new object which is based on a class, which is then its base class.
Instances inherit all methods and fields from their base class, but as I wrote above, they may either each have their own or share one (which is then considered as if it remains in the base class).
Enough talking. Let's see some code:
:Class cl
:field f←'f'
:field public fp←'fp'
:field shared fs←'fs'
:field public shared fps←'fps'
∇ r←look
:Access public shared
r←⎕NL -⍳9
∇
:EndClass
The above is a script for a class called cl
.
You can see that it has four fields and one method (function).
the first field, f
, has all the defaults, i.e. it is private, and for each instance.
The second field, fp
can be seen from outside each instance.
The third, fs
, is private, but shared among all instances (and their base class, cl
).
The last field, fps
is both visible to the outside public, and also shared.
The method, look
, is public and shared just like the field fps
.
@all So, if, from outside cl
, we try looking into cl
, which members do you think we can see?