Methods

Methods are defined just like a function, using the 'def' keyword, only this is done inside the class definition.

class Person
    def name(name)
        @name = name
        @age = 0
    end

    def setAge(age)
        @age = age
    end
end

person = new Person( "Brian" )
person.setAge( 20 )

Methods are called on an object using dot notation where a dot after an expression denotes calling a method on that object. All values (except null) are objects and so can have methods called on them. For example here a method is being called on the result of a times b:

a = rand( -10, 10 ) b = 20 value = (a * b).abs()

Method Overriding

If a super class has method with the same name and number of parameters as one in its super class, then this method will replace it.

class Health
    def new( hp )
        @hp = hp
    end

    def hurt( damage )
        if @hp > 0
            @hp = @hp - damage
        
            if @hp <= 0
                onDeath()
            end
        end
    end

    def getHP()
        return @hp
    end
    
    def onDeath()
        // do nothing
    end
end

class Player < Health
    def new()
        super( 10 )
    end
    
    def onDeath()
        // player death sequence
    end
end

In the above example the Player class overrides the 'onDeath' method in Health class. When the Player's hp goes below 0, then 'onDeath' is called by the Health actor. This will call Player's 'onDeath' rather than its own because the Player class also has a definition for the 'onDeath'.

See also

Constructors - Fields and Accessors - Inheritance