Wiki

root/cobra/trunk/HowTo/150-DeclareInits.cobra

Revision 2335, 2.1 KB (checked in by Chuck.Esterbrook, 2 years ago)

Improvements to the How-To's.

  • Property svn:eol-style set to native
Line 
1"""
2DeclareInits.cobra
3
4Initializers are methods that are automatically invoked when an object is
5created. (These are called "constructors" in some languages.)
6
7The syntax to declare one is:
8
9    cue init
10        # statements
11
12    cue init(ARG as TYPE)
13        # statements
14
15    cue init(ARG1 as TYPE1, ARG2 as TYPE2)
16        # statements
17
18Where the first statement is call to another initializer in the same class or
19the base class:
20
21Some key points:
22
23    * You can have 0 or more arguments.
24
25    * If you declare no initializers at all, Cobra will automatically provide
26      them to match each non-private initializer in the base class.
27
28    * If you declare even one initializer, Cobra will not automatically add any
29      more. This gives you control over how a class must be initialized.
30
31    * Initializers can be overloaded by the number and type of their arguments.
32
33    * Initializers are public by default.
34
35    * Initializers can say "base.init" or "base.init(ARGS)" to invoke
36      a base initializer.
37
38    * Initializers can say ".init" or ".init(ARGS)" to invoke
39      a fellow initialier.
40
41    * Initializers can have their own unit tests just like methods.
42"""
43
44# below are unrelated classes that demonstrate initializers:
45
46class Speaker
47    """
48    The Speaker declares no explicit initializer, but you can still create
49    Speaker objects.
50    """
51
52    test
53        sp = Speaker()  # <-- making an object
54        sp.speak  # <-- using that object
55
56    def speak
57        print 'Hello'
58
59
60class Building
61
62    test
63        b = Building(3)
64        assert b.number == 3
65        b = Building(2983)
66        assert b.number == 2983
67        # b = Building()  -- will not compile because Building only has one
68        #                    initializer which requires an int
69
70    cue init(n as int)
71        base.init
72        _number = n
73
74    get number from var as int
75
76
77class Thing
78
79    test
80        t = Thing()
81        t = Thing('Foo')
82        t = Thing(100)
83        t = Thing('Bar', 50)
84        assert t.name == 'Bar' and t.age == 50
85
86    cue init
87        .init('(NONAME)', -1)
88
89    cue init(name as String)
90        .init(name, -1)
91
92    cue init(age as int)
93        .init('(NONAME)', age)
94
95    cue init(name as String, age as int)
96        base.init
97        _name = name
98        _age = age
99
100    get name from var as String
101
102    get age from var as int
103
104
105class Program
106
107    def main
108        pass
Note: See TracBrowser for help on using the browser.