|
| """
DeclareInits.cobra
Initializers are methods that are automatically invoked when an object is
created. (These are called "constructors" in some languages.)
The syntax to declare one is:
def init
# code
def init(ARG as TYPE)
# code
def init(ARG1 as TYPE1, ARG2 as TYPE2)
# code
Some key points:
* You can have 0 or more arguments.
* If you declare no initalizers at all for a given class, Cobra will
provide one, public, parameterless initializer.
* Initializers can be overloaded by the number and type of their arguments.
* Initializers are public by default.
* Initializers can say "base.init(ARGS)" to invoke a base init.
* Initializers can say ".init" or ".init(ARGS)" to invoke a fellow init.
* Initializers can have their own unit tests just like methods.
"""
# below are unrelated classes that demonstrate initializers:
class Speaker
"""
The Speaker declares no explicit initializer, but you can still create
Speaker objects.
"""
test
sp = Speaker() # <-- making an object
sp.speak # <-- using that object
def speak
print 'Hello'
class Building
test
b = Building(3)
b = Building(2983)
# b = Building() -- would not compile because Building only has one
# initializer which requires an int
var _number as int
def init(number_ as int)
_number = number_
class Thing
test
t = Thing()
t = Thing('Foo')
t = Thing(100)
t = Thing('Bar', 50)
var _name as String
var _age as int
def init
.init('(NONAME)', -1)
def init(name as String)
.init(name, -1)
def init(age as int)
.init('(NONAME)', age)
def init(name as String, age as int)
_name = name
_age = age
def main is shared
pass |