Inheritance

Class inheritance enables you to create a new class that derives from an existing class. The derived class is called a descendant; the class it derives from is called the ancestor or base class. A descendant inherits all fields and methods from the ancestor and can add new fields and methods. Also, the descendant can change the behavior of the ancestor by overriding one or more methods.

To derive from a class, specify its name within parentheses after the name of the class. Example:

class Base {
  int x
  int func getXPlusOne()
    return x + 1
  endfunc
}

class Derived(Base) {
  int y
  int func getXPlusY()
    return x + y
  endfunc
}

The Derived class contains both the members from itself, and the members from Base. Let's test this:

Derived d = new Derived
d.x = 2
d.y = 3
print(d.getXPlusOne())  ; Prints 3
print(d.getXPlusY())    ; Prints 5

You can assign a derived object to a variable that has the type of the ancestor class, because a derived object is always compatible with its ancestor:

Derived d = new Derived
d.x = 4
d.y = 5
Base b = d
print(b.x)  ; Prints 4
print(b.y)  ; Compilation error!

Next: Fields

See Also
Classes
Casting