Debian Codegraph @

examples/type/polymorph.ck

raw
1 //---------------------------------------------------------------------
2 // name: polymorph.ck
3 // desc: example showing polymorphism using a base class and two
4 // subclasses that each implement their own play() function;
5 // a generic array of base class references is initialized
6 // with the more specific subclass instances; this allows
7 // for .play() to be called during the loop, the behavior of
8 // which can take on different forms depending on the specific
9 // type of underlying subclass.
10 //
11 // philosophically, polymorphism in programming amounts to
12 // a structured way to "break" the established contract between
13 // a type system and the programmer, allowing objects of
14 // apparently the same type to exhibit different behaviors.
15 //
16 // author: Ge Wang (https://ccrma.stanford.edu/~ge/)
17 // date: Winter 2023
18 //---------------------------------------------------------------------
19 // generic base class
20 class Motif
21 {
22 // default method to be potentially overridden in subclasses
23 fun void play()
24 {
25 <<< "base class Motif.play()", "" >>>;
26 }
27 }
28
29 // subclass that inherits from Motif
30 // can think of MoA as a more specific kind of Motif
31 class MoA extends Motif
32 {
33 // define play behavior for MoA by overriding play()
34 fun void play()
35 {
36 <<< "do Motif A", "" >>>;
37 }
38 }
39
40 // subclass that inherits from Motif
41 // can think of MoB as a more specific kind of Motif
42 class MoB extends Motif
43 {
44 // define play behavior for MoB by overriding play()
45 fun void play()
46 {
47 <<< "do Motif B", "" >>>;
48 }
49 }
50
51 // instantiate array of base class Motif references
52 // each element is a specific kind of Motif
53 [new MoA, new MoB, new MoB, new MoA] @=> Motif @ motifs[];
54
55 // array index variable
56 0 => int which;
57
58 // loop
59 while( true )
60 {
61 // will automatically call the right play() depending on
62 // the underlying type (MoA vs. MoB) as instantiated above
63 spork ~ motifs[which].play();
64
65 // advance time
66 300::ms => now;
67
68 // cycle which / print divider every cycel
69 which++; if( which >= motifs.size() )
70 { 0 => which; cherr <= "--" <= IO.newline(); }
71 }