""" 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: cue init # code cue init(ARG as TYPE) # code cue 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) assert b.number == 3 b = Building(2983) assert b.number == 2983 # b = Building() -- will not compile because Building only has one # initializer which requires an int cue init(n as int) _number = n get number from var as int class Thing test t = Thing() t = Thing('Foo') t = Thing(100) t = Thing('Bar', 50) assert t.name == 'Bar' and t.age == 50 cue init .init('(NONAME)', -1) cue init(name as String) .init(name, -1) cue init(age as int) .init('(NONAME)', age) cue init(name as String, age as int) _name = name _age = age get name from var as String get age from var as int def main is shared pass |