Accessors (properties, getter/settors) are methods that can be used to allow safe access to fields or to set or return computed or cached values.
Source:
Expand

namespace Accessor is
    use System.Exception;
    use Generic.Vector;

    class CreepyCrawly is
        String name;
        int legs;

        void init( String name, int l ) is
            Name = name;
            Legs = l;
        si

        // get accessor is called when the property is read:
        get String Name is
            return name;
        si

        // set accessor is called when the property is assigned to:
        set String Name = n is
            name = n;
        si

        // this set accessor checks its argument is acceptable before
        // it updates it:
        set int Legs = l is
            if l < 0 || l > 1000 then
                throw new LegException( "" + l + " is a silly number of legs" );
            fi
            legs = l;
        si

        get int Legs is
            return legs;
        si
        
        String toString() is
            return Name + " with " + Legs + " legs";
        si
    si

    class Main is
        // Program execution starts at Main.init():
        void init() is
            var garden = new Vector<CreepyCrawly>();

            try
                garden.add( new CreepyCrawly( "Worm", 0 ) );
                garden.add( new CreepyCrawly( "Snail", 1 ) );
                garden.add( new CreepyCrawly( "Bug", 6 ) );
                garden.add( new CreepyCrawly( "Spider", 8 ) );
                garden.add( new CreepyCrawly( "Centipede", 80 ) );

                foreach CreepyCrawly cc; garden.Iterator do
                    IO.Std.out.println( "this " + cc.Name + " has " + cc.Legs + " legs" );
                od
            catch LegException le
                IO.Std.out.println( "shouldn't happen: silly number of legs\n" + le );
            yrt         
        si
    si

    class LegException isa Exception is
        void init(String msg) is
            super.init(msg);  
        si
    si
si
Output:
Expand
this Worm has 0 legs
this Snail has 1 legs
this Bug has 6 legs
this Spider has 8 legs
this Centipede has 80 legs
site design and content copyright (C) jeek 1995-2010     [ 13132 ]