Constructors

Any method called 'new' is a constructor, and this is called automatically when the class is created.

// a class with no methods
class Person
    def new()
        @name = "unknown"
    end

    def new(name)
        // a name field
        @name = name
    end
end

// creates an instance of Person
person = new Person( "Brian" )

If no constructor is defined then a default constructor with no parameters is automatically defined.

Calling Super Constructors

To initialize the super class you need to call it's constructor from your constructor. This is done by calling 'super' and passing in the parameters.

class Cactus
    def new( numSpikes )
        @numSpikes = numSpikes
    end
    
    def new()
        @numSpikes = 1000
    end
end

class SuperCactus < Cactus
    dew new( numSpikes )
        super( numSpikes )
    end
    
    def new()
        super()
    end
end

In the above example each constructor in the SuperCactus calls up to its super-class constructor.

See also

Methods - Fields and Accessors - Inheritance