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.
def new( hp )
@hp = hp
def hurt( damage )
@hp = @hp - damage
class Player < Health
super( 10 )
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.
Fields are to the class they are defined in. They cannot be accessed by any sub-class. For example:
def new( name )
@name = name
class Pet < Animal
def new( species, name )
super( species )
@name = name
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.
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).
return 'Chunky Bacon'
return 'I am a Fox!'
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.