A Tour of Morfa

Inheritance

To create a hierarchy of classes in Morfa and use object-oriented programming facilities one uses fairly standard inheritance mechanisms. The key points are:

  • Inherit from at most one class and implement any number of interfaces

  • All classes are derived from built-in Object class declared in the library module object. Refer to this module file to learn the built-in methods of every class, which may be overriden.

To indicate inheritance use : in class definition.

class Base
{
    public func new()
    {
    }

    public func f(): text
    {
        return "Base.f";
    }

    public abstract func g(): text;
}

class Derived : Base
{
    public func new()
    {
        super.new();
    }

    public override func f(): text
    {
        return "Derived.f";
    }

    public override func g(): text
    {
        return "Derived.g";
    }
}

unittest
{
    var object: Base = new Derived();
    object.f();
}

In the above example you may notice also the use of abstract modifier to indicate a method with no implementation in Base—classes deriving from Base must implement g to be instantiated. Also note the override modifier which is required in Morfa.

A class may derive from only one class, but may "derive from" (implement) many interfaces like this:

public interface Interface
{
    public func h(): text;
}

public interface Printable
{
    public func print(): void;
}

public class Implementation: Interface, Printable
{
    public override func h(): text
    {
        return "Implementation.h";
    }

    public override func print(): void
    {
        // ...
    }
}

Anonymous classes

Anonymous classes can be used if there is no need to define a separate class, but we need to use an instance derivinig from specific class/interface:

public func iNeedAPrintable(somePrintable: Printable): void
{
    somePrintable.print();
}

unittest
{
    iNeedAPrintable(new class Printable
    {
        public override func print(): void
        {
        }
    });
}

Here, the argument passed to iNeedAPrintable is an instance of some anonymous class implementing Printable.

A class may be marked as final to avoid it being derived from. A class may be marked as abstract to indicate that all its methods are abstract.