- CLOS stands for Common Lisp Object System. It
is the Common Lisp mechanism that supports object
oriented programming.
- Declaring a Class. The class book inherits
from no other classes. Each member of the class contains
two data fields: pages and author. The pages
to the left of :accessor is the
internal field name. The pages to
the right of :accessor is how you will access the internal
field name. For simplicity, I always make these two names
the same!
(defclass book ()
(
(pages :accessor pages)
(author :accessor author)
)
)
- Instantiating a Class
(setf my-book (make-instance 'book))
- Accessing the Data Members
(setf (pages my-book) 200)
(setf (author my-book) 'Melville)
- Writing a Method. defmethod stands for DEFine
METHOD. Pretty-Print is a method that has one parameter,
abook. The type of abook is specified to be an instance
of book.
(defmethod pretty-print ((abook book))
(format t "The author of the book: ~a~%" (author abook))
(format t "The number of pages: ~a~%" (pages abook))
)
- Calling a Method
(pretty-print my-book)
- Using Inheritance. Textbook is a subclass of
book. It will inherit all the book methods
and data members.
(defclass textbook (book)
(
(subject :accessor subject)
)
)
- Overriding Methods. To override the pretty-print
method, simply redefine it with a more specific parameter type.
In general, the most specific method that is applicable is the
one that will be called.
(defmethod pretty-print ((abook textbook))
(format t "Pages: ~a~%" (pages abook))
(format t "Author: ~a~%" (author abook))
(format t "Subject: ~a~%" (subject abook))
)
(setf nillson (make-instance 'textbook))
(setf (pages nillson) 513)
(setf (author nillson) 'nillson)
(setf (subject nillson) 'computer-science)
(pretty-print nillson) ;; calls the second version of pretty-print
(pretty-print my-book) ;; calls the first version
(pretty-print 100) ;; ERROR, neither version is applicable