Classes, Objects, and Interfaces - course.ccs.neu.edu 9.1 Classes... · methods (functions) as well...
Transcript of Classes, Objects, and Interfaces - course.ccs.neu.edu 9.1 Classes... · methods (functions) as well...
Classes,Objects,andInterfaces
CS5010ProgramDesignParadigms"Bootcamp"Lesson9.1
1©MitchellWand,2012-2015ThisworkislicensedunderaCreative Commons Attribution-NonCommercial 4.0 International License.
ModuleIntroduction
• Inthismodule,wewillseehowclasses,objects,andinterfacesfitintoouraccountofinformationanalysisanddatadesign
• We'llseehowthefunctionalandtheobject-orientedmodelsarerelated
• We'lllearnhowtoapplythedesignrecipeinanobject-orientedsetting.
2
Generalization
OverConstants
OverExpressions
OverContexts
OverDataRepresentations
OverMethodImplementations
MixedData
DataRepresentations
Basics
RecursiveData
FunctionalData
Objects&Classes
Stateful Objects
Module09
3
DesignStrategies
Combinesimplerfunctions
Useatemplate
DivideintoCases
Callamoregeneralfunction
CommunicateviaState
Recuronsubproblem(s)
Goalsofthislesson
• Learnthebasicsaboutclasses,objects,fields,andmethods.
• LearnhowtheseideasareexpressedintheRacketobjectsystem
• Weassumethatyoualreadyknowalittleaboutobject-orientedprogramming.
4
Slogansforthislesson
• Classesarelikedefine-structs,butwithmethods(functions)aswellasfields.
• Everyobjectknowsitsclass.• Invokeamethodofanobjectbysendingitamessage.
• Theinterfaceofanobjectisthesetofmessagestowhichitresponds.
• Interfacesaredatatypes
5
ClassesandObjects
• Aclassislikeadefine-struct.• Itspecifiesthenamesofthefieldsofitsobjects.
• Italsocontainssomemethods. Eachmethodhasanameandadefinition.
• TocreateanobjectofclassC,wesay(new C)
6
Yousaymorethanthis,butthisisgoodenoughright
now.
Whatisanobject?• Anobjectisanotherwayofrepresentingcompounddata,like
astruct.• Likeastruct,ithasfields.• Ithasonebuilt-infield,calledthis,whichalwaysreferstothis
object• Herearepicturesoftwosimpleobjects:
7
x = 10y = 20r = 10this =
h = 30w = 15color = "blue"this =
Weassumethatyou've seensomekindofobject-orientedprogrammingbefore,sowe'rejustreviewingvocabularyhere.
Ifyou'vereallyneverusedOOPbefore,godosomeoutsidereadingbeforecontinuing.
Everyobjectknowsitsclass(1)
8
x = 10y = 20r = 10
x = 15y = 35r = 5
(class* object% () (init-field x y r)(define/public (foo) (+ x y))(define/public (bar n) (+ r n))...)
Herearetwoobjectsofthesameclass.Intheclassdefinition,theinit-fielddeclarationspecifiesthateachobjectofthisclasshas3fields,namedx,y,andr.Theclassdefinitionalsodefinestwomethods,namedfoo andbar,thatareapplicabletoanyobjectofthisclass.
Theseobjectsalsohaveathisfield,butwedon'tshowit
unlessweneedto.
Howdoyoucomputewithanobject?
• Toinvokeamethodofanobject,wesendtheobjectamessage.
• Forexample,toinvoketheareamethodofanobjectobj1,wewrite
(send obj1 area)• Ifobj1 isanobjectofclassC,thisinvokestheareamethodinclassC.
9
Everyobjectknowsitsclass(2)
10
x = 10y = 20r = 10
x = 15y = 35r = 5
(class* object% () (init-field x y r)(define/public (foo) (+ x y))(define/public (bar n) (+ r n))...)
obj1
obj2 Thevariablesinthemethoddeclarationsrefertothefieldsintheobject.So:
(sendobj1foo)returns30(sendobj2foo)returns50
Everyobjectknowsitsclass(3)
11
x = 10y = 20r = 10
x = 15y = 35r = 5
(class* object% () (init-field x y r)(define/public (foo) (+ x y))(define/public (bar n) (+ r n))...)
obj1
obj2 Methodscanalsotakearguments,justlikefunctions.So
(sendobj1bar8)returns18(sendobj2bar8)returns13
Everyobjectknowsitsclass(4)
12
(class* object% () (init-field x y r)(define/public (foo) (+ x y))(define/public (bar n) (+ r n))(define/public (baz n) (+ (send this foo)
n))...)
MethodsarejustRacketfunctions,sotheycandoanythingaRacketfunctioncando,includingsendmessagestoobjects.
(sendobj1baz 20)returns(+3020)=50(sendobj2baz 20)returns(+5020)=70
x = 10y = 20r = 10this =
obj1x = 15y = 35r = 5this =
obj2
Everyobjectknowsitsclass(5)
13
(class* object% () (init-field x y r)(define/public (foo) (+ x y))(define/public (bar n) (+ r n))(define/public (baz n) (+ (send this foo)
n))...)
obj2obj1
x = 10y = 20r = 10this =
x = 15y = 35r = 5this =
a = 15b = 35c = 5this =
(class* object% () (init-field a b c)(define/public (foo) (+ a b))(define/public (bar n) (* c n))(define/public (baz n)
(+ (send this foo) n))...)
obj3
Here'sanotherobject,obj3,ofadifferentclass.Ifwesendamessagetoobj3,thenobj3'smethodswillbeinvoked.
Everyobjectknowsitsclass(6)
14
(class* object% () (init-field x y r)(define/public (foo) (+ x y))(define/public (bar n) (+ r n))(define/public (baz n) (+ (send this foo)
n))...)
obj2obj1
x = 10y = 20r = 10this =
x = 15y = 35r = 5this = So
(sendobj2bar8)=(+58)=13(sendobj3bar8)=(*58)=40
a = 15b = 35c = 5this =
(class* object% () (init-field a b c)(define/public (foo) (+ a b))(define/public (bar n) (* c n))(define/public (baz n)
(+ (send this foo) n))...)
obj3
Theimportantthingaboutanobjectiswhatmethodsitrespondsto
• SoifIwrote(define (foo1 x) (send x bar 8))
• Icouldcallfoo1 onobj1,obj2,orobj3,becauseallofthemrespondtothebarmessagewithanintegerargument.
• Thecontractforfoo1 shouldspecifythatitsargumentwillacceptabarmessagewithanintegerargument.
15
Interfacesaredatatypes
• Thesetofmessagestowhichanobjectresponds(alongwiththeircontracts)iscalleditsinterface.
• Sothecontractforfoo1 (oranyotherfunctionthattakesanobjectasanargument)shouldbeexpressedintermsofinterfaces.
• SointerfacesplaytheroleofdatatypesintheOOPsetting.
16
UsingTheRacketClassSystem
• WewillusefullRacket(yay!)• Write
#lang racketatthebeginningofeachfile• AndsettheLanguagelevelto"DetermineLanguagefromSource"
17
Interfacedefinition#lang racket
(require "extras.rkt")(require rackunit)
;; examples from Lesson 9.1
(define Interface1<%>(interface ()
foo ; -> Intbar ; Int -> Intbaz ; Int -> Int))
18
InRacket,namesofinterfacesendwith<%> (by
convention)
Ignorethat ()fornow
Wewritedowneachmethodname,withitscontractasacomment.We
canwritetheminanyorder
foo isafunctionofnoarguments (legalin#lang racket)
AClassDefinition(1)(define Class1%
(class* object% (Interface1<%>)
(init-field x y r) ;; x,y,r : Int
(super-new) ;; required magic
;; foo : -> Int(define/public (foo) (+ x y))
;; bar : Int -> Int(define/public (bar n) (+ r n))
;; baz : Int -> Int(define/public (baz n) (+ (send this foo) n))
))
19
Thismeansthatthisclassissupposed toimplementInterface1<%>. Ifweleaveoffoneofthemethods,we’llgetanerrormessage.
x,y,andr arethefieldnames.We’veputintheircontractsasacomment.Inarealexample,you’dputaninterpretation foreachfield,justasyoudothefields ofastruct.
object%and(super-new)arerequiredmagic.We’lllearnabouttheminalatermodule
AClassDefinition(2)(define Class1%
(class* object% (Interface1<%>)
(init-field x y r) ;; x,y,r : Int
(super-new) ;; required magic
;; foo : -> Int(define/public (foo) (+ x y))
;; bar : Int -> Int(define/public (bar n) (+ r n))
;; baz : Int -> Int(define/public (baz n) (+ (send this foo) n))
))
20
Weusedefine/public todefinemethods.Herewe’vewrittenthe
contractforeachmethod; laterwe’llseewhattheDesignRecipedeliverablesformethodsare.
Anotherclassdefinition(define Class2%(class* object% (Interface1<%>)
(init-field a b c) ; a, b, c : Int
(super-new)
;; foo : -> Int(define/public (foo) (+ a b))
;; bar : Int -> Int(define/public (bar n) (* c n))
;; baz : Int -> Int(define/public (baz n)
(+ (send this foo) n))
))
21
Here’sthedefinition ofClass2%.Observethatithasdifferent fieldnames,butthesamemethodnames.Themethoddefinitions refertothe
newfieldnames.
Yetanotherclassdefinition(define Class2%(class* object% (Interface1<%>)
(init-field a b c) ; a, b, c : Int
(super-new)
;; foo : -> Int(define/public (foo) (+ a b))
;; bar : Int -> Int(define/public (bar n) (* c n))
;; baz : Int -> Int(define/public (baz n) (+ (send this foo) n))
))
(define Class2a%(class* object% (Interface1<%>)
(init-field a b c) ; a, b, c : Int
; add a new field, initialized to (– a)(field [a1 (- a)])
(super-new)
;; foo : -> Int(define/public (foo) (- b a1))
;; bar : Int -> Int(define/public (bar n) (* c n))
;; baz : Int -> Int(define/public (baz n) (+ (send this foo) n))
))
22
ObjectsofClass2%andClass2a%arebuiltthesamewayandgivethesameanswerforeverymethodcall.Anyprocedure thatworkswithonewillworkthesamewaywiththe
other.
Thisisanotherreasonwewritecontractsintermsofinterfaces,not
classes.
Creatingobjectsandtesting(define obj1 (new Class1% [x 10][y 20][r 10]))(define obj2 (new Class1% [y 35][x 15][r 5]))(define obj3 (new Class2% [a 15][b 35][c 5]))
(begin-for-test
(check-equal? (send obj1 foo) 30)(check-equal? (send obj2 foo) 50)
(check-equal? (send obj1 bar 8) 18)(check-equal? (send obj2 bar 8) 13)
(check-equal? (send obj1 baz 20) 50)(check-equal? (send obj2 baz 20) 70)
(check-equal? (send obj2 bar 8) 13)(check-equal? (send obj3 bar 8) 40)
)
23
Hereisthesyntaxforcreatingobjects.The
fieldscanbelistedinanyorder.
Andherewesendtheobjectssomemessagesandcheckthattheresultsareaswepredicted
ontheslidesabove.
LessonSummary
• Inthislessonwe’velearned:– Classesarelikedefine-structs,butwithmethods(functions)aswellasfields.
– Everyobjectknowsitsclass.– Invokeamethodofanobjectbysendingitamessage.– Theinterfaceofanobjectisthesetofmessagestowhichitresponds.
– Interfacesaredatatypes.• We’veseenhowtodefineclasses,objects,andinterfacesintheRacketobjectsystem.
24