DOC PREVIEW
Berkeley COMPSCI 164 - Lecture Notes

This preview shows page 1-2-3-19-20-39-40-41 out of 41 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 41 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 41 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 41 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 41 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 41 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 41 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 41 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 41 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 41 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

Slide 1AnnouncementWhere are we?Objects (review from CS61B)Our Design RationaleSlide 6We have seen closure-based objects alreadyUse of single-method objectMulti-method object represented as a closureSlide 10Recall tablesObject as a table of attributesSugar designSyntactic sugarObject as a table of attributes, revisitedIntroduce selfThe colon notationRewriting E:ID()DiscussionSlide 20The __index metamethodSlide 22What runtime setup do we want?Create an objectNote about cs164 projectsSlide 26Inheritance allows reuse of code …Must set this up in the constructorDefine a classCreate subclass of AccountDiscussion of prototype-based inheritanceSlide 32Slide 33Our goalLanguage Design ExcerciseObject is a table of methodsUse of this objectDiscussion of Table of methods approachWe can safely change the implementationMore discussionReading1Lecture 14Data AbstractionObjects, inheritance, prototypesRas Bodik Shaon BarmanThibaud HottelierHack Your Language!CS164: Introduction to Programming Languages and Compilers, Spring 2012UC BerkeleyAnnouncementRas will hold a review tomorrow 11-12 in the Woztopics: parsing and coroutines; bring your questionsProject Proposals due SundayI will post remaining slides tonight2Where are we?Our new constructs concerned control abstraction:→ hiding complex (changes) to program control flow under suitable programming constructs-lazy iterators, built on coroutines-backtracking in regexes, built with coroutines-search for a proof tree, hidden in the Prolog interpreterThere must also be data abstraction. A few examples:3Objects (review from CS61B)Why objects?abstraction: hide implementation under encapsulationWhy inheritance?reuse: specialization of an object’s behavior reuses its code4Our Design RationaleWe want to support objectsWhat is the minimum base language to support objects?Our language already supports closureswhich are similar in that they carry state and codeCan we build objects from this existing mechanism?rather than adding support for objects into base language?5Single-Method Approach6We have seen closure-based objects alreadyWhere did we use closures as objects?Iterators are single-method objectson each call, iterators return the next element and “advance” their iterator state7Use of single-method object d = newObject(0) print d("get") --> 0 d("set", 10) print d("get") --> 108Multi-method object represented as a closurefunction newObject (value) function (action, v) { if (action == "get“) { value } else if (action == "set“) { value = v } else { error("invalid action")} } } 9Objects as tables10Recall tablesCreate a table{}{ key1 = value1, key2 = value2 }Add a key-value pair to table (or overwrite a k/w pair)t = {}t[key] = valueRead a value given a keyx = t[key]11Object as a table of attributesAccount = {balance = 0}Account[“withdraw”] = function(v) { Account[“balance”] = Account[“balance”] - v}Account[“withdraw”](100.00) What syntactic sugar we add to clean this up?12Sugar design13Syntactic sugarp.f → p[“f”] → get(p, “f”)Careful: we need to distinguish between reading p.f translated to getand writing into p.f translated to put14Object as a table of attributes, revisitedAccount = {balance = 0}function Account.withdraw (v) { Account.balance = Account.balance - v}Account.withdraw(100.00) a = Account Account = nila.withdraw(100.00) -- ERROR!15Introduce selfAccount = {balance = 0}function Account.withdraw (self, v) { self.balance = self.balance - v}a1 = AccountAccount = nila1.withdraw(a1, 100.00) -- OKa2 = {balance=0, withdraw = Account.withdraw}a2.withdraw(a2, 260.00)16The colon notationfunction Account:withdraw (v) { self.balance = self.balance - v}3a:withdraw(100.00)How to desugar?17Rewriting E:ID()18DiscussionWhat is the inefficiency of our current objects?too much space wasted by each object carrying its objects and fields that are constant across many objects19Meta-Methods20The __index metamethodWhen a lookup of a field fails, interpreter consults the __index field:setmetatable(a, {__index = b})21Prototypespoor man’s classes22What runtime setup do we want?A prototype is an object that behaves like a class23Create an objectfunction Account:new (o) { -- create object if user does not provide one o = o or {} setmetatable(o,self) self.__index = self o}a = Account:new({balance = 0})a:deposit(100.00)24Note about cs164 projectsWe may decide not to use metatables, just the __index field. The codefunction Account:new (o) { o = o or {} setmetatable(o,self) self.__index = self o}Would become function Account:new (o) { o = o or {} o.__index = self o }25Inheritance26Inheritance allows reuse of code …… by specializing existing class (prototype)How to accomplish this with a little “code wiring”?Let’s draw the desired run-time organization:Assume class A, subclass B, and b an instance of B27Must set this up in the constructorTasks that we need to perform28Define a classAccount = {balance = 0} function Account:new (o) { o = o or {} setmetatable(o, sel) self.__index = self o}function Account:deposit (v) { self.balance = self.balance + v } function Account:withdraw (v) { if (v > self.balance) { error"insufficient funds" } self.balance = self.balance - v}29Create subclass of AccountSpecialAccount = Account:new()s = SpecialAccount:new({limit=1000.00})s:deposit(100.00)function SpecialAccount:withdraw (v) if (v - self.balance >= self:getLimit()) { error"insufficient funds" } self.balance = self.balance - v}function SpecialAccount:getLimit () { self.limit or 0}30Discussion of prototype-based inheritance Notice the sharing: constant-value object attributes (fields) remain stored in the prototype until they are assigned.After assignment, the object stores the attribute rather than finding it in the prototype31Multiple Inheritance32“Privacy”protecting the implementation33Our goalSupport large programmer teams.Bad scenario: –programmer A implements an object O–programmer B uses O relying on internal details of O–programmer A changes how O is implemented–the program now crashes on customer’s machineHow do OO languages address this problem?-private fields 34Language Design ExcerciseYour task: design an analogue of private fields Lua/164 supports meta-programmingit should allow building your own private fields35Object is a table of methods function newAccount (initialBalance)


View Full Document

Berkeley COMPSCI 164 - Lecture Notes

Documents in this Course
Lecture 8

Lecture 8

40 pages

Load more
Download Lecture Notes
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Lecture Notes and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Lecture Notes 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?