Inheritance

To help reuse classes you can have one class extend another. This is achieved by using the left arrow (the < symbol) for denoting that you 'extend' another class.

Note that you are only allowed to extend 1 class.

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

    def hurt( damage )
        @hp = @hp - damage
    end

    def getHP()
        return @hp
    end
end

class Player < Health
    def new()
        super( 10 )
    end
end

user = new Player()
user.hurt( 4 )

In the above example the Player class receives all of the properties of the Health class. This allows you to call any method in Health class on instances of Player.

Inheritance and Fields

Fields are to the class they are defined in. They cannot be accessed by any sub-class. For example:

class Animal
    def new( name )
        @name = name
    end
    
    def getSpecies()
        return @name
    end
end

class Pet < Animal
    def new( species, name )
        super( species )
        
        @name = name
    end
    
    def getName()
        return @name
    end
end

myCat = new Pet( "Cat", "Ming" )
myCat.getSpecies() // returns 'Cat'
myCat.getName() // returns 'Ming'

Setting a value to the 'name' in the Pet class has no effect on the 'name' field in its super Animal class.

The motivation behind this is because it is generally considered bad practice to access fields outside of your own class. Like in the example above; this also helps to avoid accidental conflicts between fields in different classes.

The Object Class

If a class does not extend another class, then it will automatically extend the 'Object' class.

This means that anything defined in Object will be available in all classes, since everything is a sub-class of Object (either directly or in-directly).

class Object
    def blah()
        return 'Chunky Bacon'
    end
end

class Pet
    def blah()
        return 'I am a Fox!'
    end
end

class Other
end

something = new Other()
something.blah() // returns 'Chunky Bacon'

5.blah()      // returns 'Chunky Bacon'
"cats".blah() // returns 'Chunky Bacon'

pet = new Pet()
pet.blah() // returns 'I am a Fox!'

The method 'blah' is available on every object because it is defined in the Object class.

See also

Methods - Constructors - Fields and Accessors