Objects

Tcl has classes and objects in oo::class. An object is a command, and a method is a subcommand of it. This lesson makes a Note class for jot.

A class

oo::class create Note {
    variable text done
    constructor {t} {
        set text $t
        set done 0
    }
    method text {} { return $text }
    method done {} { set done 1; return $text }
    method show {} { return "\[[expr {$done ? "x" : " "}]\] $text" }
}
oo::class create Todo {
    superclass Note
    variable due
    constructor {t d} {
        next $t
        set due $d
    }
    method show {} { return "[next] (due $due)" }
}

variable text done makes the two names the variables of each object. Note create milk "buy milk" makes an object with a name, and milk show calls a method. milk done changes it, and milk show shows the change. Note new "text" makes an object with a name that ztcl picks, such as ::oo::Obj4. Keep that name in a variable.

A wrong method is an error with the list of the methods: milk nope. my calls a method of the same object from the inside: my show.

A subclass

Todo in the box is a subclass. superclass names the parent class, and next calls the method of the same name in the parent. [Todo new "call Ada" friday] show makes a Todo and shows it.

Look inside an object

info object class milk gives the class. info class methods Note lists the methods. milk destroy removes the object and its command. An object stays until destroy: an object that the code makes and forgets uses memory until the interpreter ends.

Reading code an agent wrote

Ask an agent

Make jot keep each note as an object of the class Note, with the methods text, done, and show. Destroy the object when jot remove removes a note.

Try this