Object Oriented Programming

The structures and behaviors of objects are described in classes, which are defined by defclass macro and defmethod special form. defclass defines the name of the class, its super class, and slot variable names, optionally with their types and message forwarding. defmethod defines methods which will invoked when corresponding messages are sent. Class definition is assigned to the symbol's special value. You may think of class as the counter part of Common Lisp's structure. Slot accessing functions and setf methods are automatically defined for each slot by defclass.

Most classes are instantiated from the built-in class metaclass. Class vector-class, which is a subclass of metaclass, is a metaclass for vectors. If you need to use class-variables and class-methods, you may make your own metaclass by subclassing metaclass, and the metaclass name should be given to defclass with :metaclass keyword.

Vectors are different from other record-like objects because an instance of the vector can have arbitrary number of elements, while record-like objects have fixed number of slots. EusLisp's object is either a record-like object or a vector, not both at the same time.

Vectors whose elements are typed or the number of elements are unchangeable can also be defined by defclass. In the following example, class intvec5 which has five integer elements is defined. Automatic type check and conversion are performed when the elements are accessed by the interpreter. When compiled with proper declaration, faster accessing code is produced.

(defclass intvec5 :super vector :element-type :integer :size 5)
(setq x (instantiate intvec5))  --> #i(0 0 0 0 0)

When a message is sent to an object, the corresponding method is searched for, first in its class, and next in its superclasses toward object, until all superclasses are exhausted. If the method is undefined, forward list is searched. This forwarding mechanism is introduced to simulate multiple inheritance. If the search fails again, a method named :nomethod is searched, and the method is invoked with a list of all the arguments. In the following example, the messages :telephone and :mail are sent to secretary slot object which is typed person, and :go-home message is sent to chauffeur slot.

(defclass president :super object
                    :slots ((name :type string)
                            (age  :type :integer)
                            (secretary  :type person
                                        :forward (:telephone :mail))
                            (chauffeur  :forward (:go-home))))

In a method, two more local variables, class and self, become accessible. You should not change either of these variables. If you do that, the ones supplied by the system are hidden, and send-super and send self are confused.



Subsections
k-okada 2013-05-21