Lecture 22
Introduction to Racket Object-Oriented Programming (OOP)
Programming Languages
UW CSE 341 - Autumn 2021
Racket Has Classes and Objects (In Case You’re Into That Sort of Thing)
Documentation
A Note on the Homework
Next homework is about understanding and extending an existing program that uses a bunch of unfamiliar features
Emphasizes how OOP uses overriding to allow for extensibility
The Rules of Class-Based OOP
Pure OOP
In “full” OOP (cf. Ruby, Smalltalk, ..):
In Java:
In Racket:
Racket Class Basics
Before we can create an object, we need a class to make instances of
Racket classes are anonymous first-class values (!!)
See the code
The next several slides may make little sense without the example class we are defining for rational numbers but can be a complementary reference
Class definitions
(class superclass …) form may take some getting used to
Flavors of things in the …:
Defining object construction
Doing object construction
Clients instantiate a class with (new foo% …) where the … provides initialization parameters by name.
Result is an object that is an instance of the class
Using objects
(send obj msg arg1 … argN)
msg is the name of a public method defined by the class that obj is an instance of
Why private state
(define kelvin-temp …)
(define/public (set-celsius-temp! t)
(set! kelvin-temp (- t 273.15)))
(define/public (possible-temp?) (> kelvin-temp 0))
Our example: objects aren’t modules
rational% “works fine enough” but it has a “cheat” compared to our similar example with OCaml modules
this
this is a special word that means “the current object” (same as Java)
Sending messages to this makes a lot of sense (see isWhole, double!):
Can also use this like any other expression - pass “yourself” as an argument, store in a data structure, etc. (see double!)
Inheritance
In a subclass:
But if subclass definition includes (inherit foo), two things change:
What about overriding?
Yep, overriding is an essential aspect of OOP.
Stay tuned! See section and the next lecture.