Links

Categories

Tags


« | Main | »

Accessor methods

By Jewe | October 29, 2012

import stdlib;
using stdlib;

// a class with "properties"
class Person
{
    method Person(string name, int age)
    {
        // set member variables
        Name = name;
        Age = age;
    }
    // "getter" hides and returns member variable 'Name'
    accessor string Name()
    {
        return Name;
    }
    // "setter" hides and sets member variable 'Name'
    accessor Name(string n)
    {
        Name = n;
    }
    // "getter" hides and returns member variable 'Age'
    accessor int Age()
    {
        return Age;
    }
    // member variables
    string Name;
    int Age;
}

function string main(const string[] args)
{
    Person p = new Person("Rick", 23);

    println("p's name is " + p.Name);   // calls "getter"
    println("p's age is " + p.Age);     // calls "getter"

    p.Name = "Chris";                   // calls "setter"
    p.Age = 34;                         // ERROR: No "setter" defined in class
    return null;
}

Topics: code examples | Comments Off on Accessor methods

Comments are closed.