""" 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 # statements cue init(ARG as TYPE) # statements cue init(ARG1 as TYPE1, ARG2 as TYPE2) # statements Where the first statement is call to another initializer in the same class or the base class: Some key points: * You can have 0 or more arguments. * If you declare no initializers at all, Cobra will automatically provide them to match each non-private initializer in the base class. * If you declare even one initializer, Cobra will not automatically add any more. This gives you control over how a class must be initialized. * Initializers can be overloaded by the number and type of their arguments. * Initializers are public by default. * Initializers can say "base.init" or "base.init(ARGS)" to invoke a base initializer. * Initializers can say ".init" or ".init(ARGS)" to invoke a fellow initialier. * 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) base.init _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) base.init _name = name _age = age get name from var as String get age from var as int class Program def main pass |
How To Declare Inits