Object Orientation

In most OOP systems, methods belong to classes. In Common Lisp, methods are instances of generic functions, which can dispatch on not just the first argument, but every argument. This makes functions, rather than classes, the prime mover.

Generic Functions and Methods

We define a generic function with defgeneric:

(defgenericdescription(object)(:documentation"Return a description of an object."))

And we define methods of that function with defmethod:

(defmethoddescription((objectinteger))(formatnil"The integer ~D"object))(defmethoddescription((objectfloat))(formatnil"The float ~3,3f"object))

We can try them in the REPL:

CL-USER>(description10)"The integer 10"CL-USER>(description3.14)"The float 3.140"

Classes

(defclassvehicle()((speed:accessorvehicle-speed:initarg:speed:typereal:documentation"The vehicle's current speed."))(:documentation"The base class of vehicles."))

When the superclass list is empty, the default base class, standard-class, is used. You can change this, but that’s an advanced topic.

(defclassbicycle(vehicle)((mass:readerbicycle-mass:initarg:mass:typereal:documentation"The bike's mass."))(:documentation"A bicycle."))(defclasscanoe(vehicle)((rowers:readercanoe-rowers:initarg:rowers:initform0:type(integer0):documentation"The number of rowers."))(:documentation"A canoe."))

Instantiate:

CL-USER>(defparametercanoe(make-instance'canoe:speed10:rowers6))CANOECL-USER>(class-ofcanoe)#<STANDARD-CLASSCOMMON-LISP-USER::CANOE>CL-USER>(canoe-rowerscanoe)6CL-USER>(vehicle-speedcanoe)10

We can get information about a class using describe:

CL-USER>(describe'canoe)COMMON-LISP-USER::CANOE[symbol]CANOEnamesthestandard-class#<STANDARD-CLASSCOMMON-LISP-USER::CANOE>:Documentation:Acanoe.Directsuperclasses:VEHICLENosubclasses.Notyetfinalized.Directslots:ROWERSType:(INTEGER0)Initargs::ROWERSInitform:0Readers:CANOE-ROWERSDocumentation:Thenumberofrowers.
close