Announcements

Quizzes available in recitation tomorrow

Read chapters 1-3 of "Learn Java Now"

Have a very nice vacation!

Conventions for Object-Oriented Programming

  1. OO Programming is about conventions for handling local state:

    Terminology for Object-Oriented Programming

  2. Terminology: Access to state is via objects. An object can receive messages, and has access to various methods for responding to them.
  3. Terminology: Objects are created by classes, which specify what state is to be created when a new object is created, what messages the object will process, which methods it will use to process those messages, and what to do if the object receives a message for which it has no method.
  4. The classes are related to each other through inheritance or delegation. We'll explore delegation (it's a bit more powerful) but Java uses inheritance.
  5. In Scheme, objects and classes are both procedures. The local state is stored in the frames that are created when the procedures are called. This is also true of Java.

Pairs as Objects

(define (make-pair L R)
  (lambda (msg)
    (case msg
      ((LEFT) L)
      ((RIGHT) R)
      ((NEW-LEFT!) (lambda (new) (set! L new)))
      ((NEW-RIGHT!) (lambda (new) (set! R new))))))

Basic Operations for Objects

(define (get-method-from-object message object)
  (object message))

(define get-method     ; Simplification
   get-method-from-object)

(define no-method
  (let ((tag (list 'NO-METHOD)))
    (lambda () tag)))

(define (method? x)
  (cond ((procedure? x) #T)
        ((eq? x (no-method)) #F)
        (else
          (error
             "Object returned this non-message:" x))))

Pairs With Conventions

(define (make-pair L R)
  (lambda (msg)
    (case msg
      ((LEFT) (lambda () L)
      ((RIGHT) (lambda () R)
      ((NEW-LEFT!) (lambda (new) (set! L new)))
      ((NEW-RIGHT!) (lambda (new) (set! R new)))
      (else (no-method)))))))

Named Objects

(define (make-named-object name)
  ;; All objects deletegate to this, so we are 
  ;; guaranteed that any object can respond to the
  ;; messages NAME, INSTALL, and SAY.
 (lambda (message)
   (case message
     ((NAMED-OBJECT?) (lambda (self) #T))
     ((NAME) (lambda (self) name))
     ((SAY)
      (lambda (self list-of-stuff)
        (if (not (null? list-of-stuff))
            (display-message list-of-stuff))
        'NUF-SAID))
     ((INSTALL) (lambda (self) 'INSTALLED))
     (else (no-method))))))

Places delegate to Named-Object

(define (make-place name)
  (let ((neighbor-map '())           ; Alist, direction -> object
        (things       '())
        (named-obj (make-named-object name)))
   (lambda (message)
     (case message
       ((PLACE?) (lambda (self) #T))
       ...
       (else (get-method message named-obj)))))))