page

Classes

VERSIONlatest Object-Oriented Programming in Sncode

Classes

NAME

classes - Object-Oriented Programming in Sncode.

DESCRIPTION

Declaration

class Name
    method Name()
    endm
endc

Instanciation

a = new Name();

Methods

Methods are special functions that define the behaviors of your class. A class must have at least one method called the constructor which is named the same as the class itself. This method is where you generally put your initialization tasks.

You can define and use your own methods the same way you would do with functions, but using the keywords method and endm instead.

Properties

Properties are variables that are bound to an instance of a class. They can be defined and used from any method in the class by using this:

class Person
    method Person(age)
        this.age = age;
    endm
    method birthday()
        this.age++;
    endm
endc

Properties, unlike local variables, are visible from the outside by manipulating the instance of your class like an associative array:

tom = new Person(20);
"Tom's age: "; tom.age;
Info: When you call a method, a pointer to the instance of the class is passed as a hidden magic argument and that's why you can use the variable this from inside.

EXAMPLES

Method calls

How to call a method on a class instance:

a = new MyClass();
a.myMethod();

How to call a method from another method of a class instance:

class Person
    // ...
    method setAge(value)
        this.age = value;
    endm
    method birthday()
        // like for properties, use 'this' to access methods
        this.setAge(this.age + 1);
    endm
endc

Namespacing

How to use packages as namespaces for classes:

// declaration
package MyPackage
    class MyClass
        // ...
    endc

    class MySecondClass
    endc
endp

// instanciation
a = new MyPackage::MyClass();

When you have more then one class in your package, it is recommended to put them in separate files:

mypackage/myclass.sn

package MyPackage
    class MyClass
        // ...
    endc
endp

mypackage/mysecondclass.sn

package MyPackage
    class MySecondClass
        // ...
    endc
endp

You may now include the class(es) you need:

%include "/path/to/mypackage/mysecondclass.sn";

AUTHOR

Written by Jean-Georges Guenard, <jg@sednove.com>