next up previous contents
Next: Inheritance Up: Classes Previous: Classes   Contents


The body of a class definition consists of a list of feature definitions. A feature is either an attribute or a method. An attribute of class A specifies a variable that is part of the state of objects of class A. A method of class A is a procedure that may manipulate the variables and objects of class A.

One of the major themes of modern programming languages is information hiding, which is the idea that certain aspects of a data type's implementation should be abstract and hidden from users of the data type. Cool supports information hiding through a simple mechanism: all attributes have scope local to the class, and all methods have global scope. Thus, the only way to provide access to object state in Cool is through methods.

Feature names must begin with a lowercase letter. No method name may be defined multiple times in a class, and no attribute name may be defined multiple times in a class, but a method and an attribute may have the same name.

A fragment from illustrates simple cases of both attributes and methods:

class Cons inherits List {
	xcar : Int;
	xcdr : List;

	isNil() : Bool { false };

	init(hd : Int, tl : List) : Cons {
	    xcar <- hd;
	    xcdr <- tl;
In this example, the class Cons has two attributes xcar and xcdr and two methods isNil and init. Note that the types of attributes, as well as the types of formal parameters and return types of methods, are explicitly declared by the programmer.

Given object c of class Cons and object l of class List, we can set the xcar and xcdr fields by using the method init:


This notation is object-oriented dispatch. There may be many definitions of init methods in many different classes. The dispatch looks up the class of the object c to decide which init method to invoke. Because the class of c is Cons, the init method in the Cons class is invoked. Within the invocation, the variables xcar and xcdr refer to c's attributes. The special variable self refers to the object on which the method was dispatched, which, in the example, is c itself.

There is a special form new C that generates a fresh object of class C. An object can be thought of as a record that has a slot for each of the attributes of the class as well as pointers to the methods of the class. A typical dispatch for the init method is:

(new Cons).init(1,new Nil)
This example creates a new cons cell and initializes the ``car'' of the cons cell to be 1 and the ``cdr'' to be new Nil.2 There is no mechanism in Cool for programmers to deallocate objects. Cool has automatic memory management; objects that cannot be used by the program are deallocated by a runtime garbage collector.

Attributes are discussed further in Section 5 and methods are discussed further in Section 6.

next up previous contents
Next: Inheritance Up: Classes Previous: Classes   Contents