Class Variables

Gamma: Version 4.0
Prev | Chapter 8. Object Oriented Programming | Next

# 8.5. Class Variables

Class variables (cvars), are non-method items that permanently belong to the class in which they are defined. One can think of a class variable as named data associated with the class. There is only ever one copy of the variable. All instances of that class share that copy. All derived classes and all the instances of the derived classes share that one copy. It is like a global variable.

Gamma has the ability to add cvars to a class at any time, using the function `class_add_cvar`. Once a class variable has been added to a class it becomes available to all new instances of that class and the derived classes. However they do not get a private copy of that variable but share one and the same variable that belongs to the class. As an example consider the `Catalog` class and its derived class, `Book`, once more.

        Gamma> class_add_cvar(Catalog,#capacity, 200);
        200
        Gamma> Catalog;
        (defclass Catalog nil [ ... (capacity . 200)][data start_date])
        Gamma> Book;
        (defclass Book Catalog [...][data (size . 0) start_date]
        Gamma> history = new(Book);
        {Book (data) (size . 0) (start_date)}

We can see that the derived class `Book` does not have a private copy of the class variable `capacity`. However this variable is available for the derived class as well as for the instances of that class:

        Gamma> Book.capacity;
        200
        Gamma> history.capacity;
        200

To set or query the value of a cvar use the class name (or the instance name) and the cvar in dot notation. Remember, though, a change to the cvar in any class or instance of `Catalog` will change it for all classes and instances of `Catalog`.

        Gamma> Book.capacity = 300;
        300
        Gamma> history.capacity;
        300
        Gamma> history.capacity = 400;
        400
        Gamma> Book.capacity;
        400
        Gamma> Catalog.capacity;
        400
        Gamma>

Prev | Home | Next
Instance Variables | Up | Constructors and Destructors

Copyright 1995-2002 by Cogent Real-Time Systems, Inc.