-
Notifications
You must be signed in to change notification settings - Fork 0
12. Inheritance
User-defined classes can be defined to extend others. As well as having their own members, they also inherit functionality from the classes they extend, which are referred to as superclasses. The following defines two classes, the second of which extends the first, and prints messages from instances of them:
/Base {
/__init__ {
/this exch def
/this .greeting exch def
this
} macro
/message {
.greeting " from Base!" ~ println
} macro
} class
/Derived Base {
/message {
.greeting " from Derived!" ~ println
} macro
} class
/base "Hello" Base new def
/derived "Hi" Derived new def
base .message # Prints "Hello from Base!"
derived .message # Prints "Hi from Derived!"
The Derived
class inherits Base
's constructor, but overrides the .message
method with another macro.
The is
keyword can be used to check if an element's type is either equal to or a subtype of the second argument:
base Base is println # Prints "true"
base Derived is println # Prints "false"
derived Base is println # Prints "true"
derived Derived is println # Prints "true"
More than one class can be extended, and the order in which the superclasses are defined determines the order in which they will be searched for inherited members. DSSL always performs a depth-first search of the class hierarchy, so the following prints Constructing Parallelogram
:
/Parallelogram {
/__init__ {
"Constructing Parallelogram" println
} macro
} class
/Rectangle Parallelogram { } class
/Rhombus Parallelogram {
/__init__ {
"Constructing Rhombus" println
} macro
} class
/Square Rectangle Rhombus { } class
/square Square new def
The list of a class's supertypes in order of their priority can be created using the .supers
method. All classes which do not explicitly extend any others will implicitly extend Object
, apart from Object
itself.