A Running Example: Employees

Sather - A Language Tutorial
Prev | Chapter 2. Classes and Objects | Next

# 2.9. A Running Example: Employees

We will illustrate the points made above by using a simple example, which will be something of a running example to be extended in later chapters. We will start here by defining a class `'EMPLOYEE'`. Please bear in mind that this example is used to illustrate various language features, not object-oriented design.

## EMPLOYEE definition

The class is composed of several attributes which hold the employee information. Various degrees of privacy are illustrated

    class EMPLOYEE is
       private attr wage:INT;
       readonly attr name:STR;
       attr id:INT;
       const high_salary:INT := 40000;

       create(a_name:STR, a_id:INT, a_wage:INT):SAME is
          res ::= new;
          res.id := a_id;
          res.name := a_name;
          res.wage := a_wage;
          return(res);
       end;

       highly_paid:BOOL is
          return wage >= high_salary;
       end;
    end;

Note the use of the special type `SAME` as the return type of the `create` routine, which denotes the current class name. `SAME` changes to mean the including class when it is included, as will be explained in the next chapter on code inclusion.

## TESTEMP definition

The employee class may be exercised using the following main class.

    class TESTEMP is
       main is
          john:EMPLOYEE := #EMPLOYEE("John",100,10000);
          peter:EMPLOYEE := #EMPLOYEE("Peter",3,10000);
          john.id := 100;           -- Set the attr "id" in john to 100
          #OUT + john.name + "\n";  -- Prints "John"
          #OUT + peter.id + "\n";   -- Prints "3"
       end;
    end;

Note that the following calls would be illegal:

    #OUT + john.wage + "\n";  -- ILLEGAL! "wage" is private
    john.name := "martha";    -- ILLEGAL! "name" is readonly

A distinguished class must be specified when a Sather program is compiled (the default is to look for a class called `MAIN`). This class must define a routine named `'main'`. When the program executes, an object of the specified type is created and `'main'` is called on it.

## Running the example

To run the above example - type the code into a file emp.sa and then run the executable 'emp'

    sacomp emp.sa -main TESTEMP -o emp

This generates the executable "emp", using the "main" routine in `TESTEMP` as its starting point. You can browse the resulting code by calling

    sabrowse emp.sa -main TESTEMP

Prev | Home | Next
Class Parameters | Up | Loops and Iterators