# STERNO - Examples

Here is a simple class and some code that uses it that demonstrates the basic features of Sterno

    package require Sterno

    # Create a named class.

    Sterno::defClass Colors {
        field red    ;# Define fields, but we didn't initialize them
        field green
        field blue

        # Constructor which sets the fields.
        method construct {r g b} {
            fimport   ;# Import all fields
            set red $r
            set green $g
            set blue $b
        }

        # Normal method that returns another instance of this class.
        method invert {} {
            fimport   ;# Import all fields
            # Use class field to make it easy to change class name
            return [$class new [expr 255-$red] [expr 255-$green] [expr 255-$blue]]
        }

        # A method with an argument
        method add {num} {
            fimport   ;# Import all fields
            set red [expr $red+$num]
            set green [expr $green+$num]
            set blue [expr $blue+$num]
        }

        # Always a useful method
        method toString {} {
            fimport   ;# Import all fields
            return "Red = $red, green = $green, blue = $blue"
        }
    }

    #
    # Sometimes its easier to add methods outside of the defClass
    # body.  Since method is just a class method, this is easy.
    #
    Colors method x11Color {} {
        fimport   ;# Import all fields
        return [format "#%02X%02X%02X" $red $green $blue]
    }

    #
    # Try if out.
    #
    puts "Trying out example code:"
    set color1 [Colors new 10 2 30]

    puts "  Color 1 is [$color1 toString]"
    puts "  Color 1 in X11 format is [$color1 x11Color]"
    set color2 [$color1 invert]
    puts "  Color 1 inverted is [$color2 toString]"

    Colors delete  ;# deletes class and all objects