next up previous contents
Next: Method overriding Up: Objects Previous: Objects   Contents


We now have a class definition, but no means yet to create instances. The language does not provide a mechanism to create instances; instead, this functionality is provided by the library. The TOM standard library contains a class State that provides the following method:

instance (id)

This class method returns a new instance of the receiving class. Thus, invoking

x = [State alloc];

will return a new instance of the State class. ``How does this help us to create Counter objects?'' you ask. By indicating that a Counter object is also a State object, which will cause the Counter objects to behave as State objects, and similar, that the Counter class behaves as the State class. This is called inheritance: every method defined by State is not only applicable to State, but also to Counter. To indicate that our Counter inherits from State, the class definition is changed to:

implementation class
Counter: State


Now any method or instance variable defined for the State class (or instance) now also applies to the Counter class (or instance). To denote the relationship between the two classes, State is called a superclass of Counter, and Counter is a subclass of State.

The methods inherited from State include the alloc method and we can now send alloc messages to the Counter class to create new Counter instances:

Counter count1 = [Counter alloc];

The return type of the alloc method is instance (id). The id type denotes the type of the receiving object, as seen by the caller. In the example, the receiver is the Counter class object, and id denotes the Counter class. The instance () modifies the type between the parentheses to indicate the instance of that type. The type of object returned by the alloc method in this example thus is `instance of the Counter class', written as Counter, which is exactly the type of the count1 variable to which the value returned is assigned.

next up previous contents
Next: Method overriding Up: Objects Previous: Objects   Contents
Pieter J. Schoenmakers tiggr at