




版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
1、CSE341: Programming LanguagesLecture 25Subtyping for OOP; bining Generics and Subtyping Dan GrossmanSpring 2013NowUse what we learned about subtyping for records and functions to understand subtyping for class-based OOPLike in Java/C#Recall:Class names are also typesSubclasses are also subtypesSubst
2、itution principle: Instance of subclass should usable in place of instance of superclassSpring 20132CSE341: Programming LanguagesAn object isObjects: mostly records holding fields and methodsFields are mutableMethods are immutable functions that also have access to selfSo could design a type system
3、using types very much like record typesSubtypes could have extra fields and methodsOverriding methods could have contravariant arguments and covariant results compared to method overriddenSound only because method “slots” are immutable!Spring 20133CSE341: Programming LanguagesActual Java/C#Compare/c
4、ontrast to what our “theory” allows:Types are class names and subtyping are explicit subclassesA subclass can add fields and methodsA subclass can override a method with a covariant return type(No contravariant arguments; instead makes it a non-overriding method of the same name)Is a subset of what
5、is sound (so also sound)(3) Is a subset of what is sound and a different choice (adding method instead of overriding)Spring 20134CSE341: Programming LanguagesClasses vs. TypesA class defines an objects behaviorSubclassing inherits behavior and changes it via extension and overridingA type describes
6、an objects methods argument/result typesA subtype is substitutable in terms of its field/method typesThese are separate concepts: try to use the terms correctlyJava/C# confuse them by requiring subclasses to be subtypesA class name is both a class and a typeConfusion is convenient in practiceSpring
7、20135CSE341: Programming LanguagesOptional: More detailsJava and C# are sound: They do not allow subtypes to do things that would lead to “method missing” or accessing a field at the wrong typeConfusing (?) Java example:Subclass can declare field name already declared by superclassTwo classes can us
8、e any two types for the field nameInstance of subclass have two fields with same name“Which field is in scope” depends on which class defined the methodSpring 20136CSE341: Programming Languagesself/this is specialRecall our Racket encoding of OOP-style“Objects” have a list of fields and a list of fu
9、nctions that take self as an explicit extra argumentSo if self/this is a function argument, is it contravariant?No, it is covariant: a method in a subclass can use fields and methods only available in the subclass: essential for OOPSound because calls always use the “whole object” for selfThis is wh
10、y coding up your own objects manually works much less well in a statically typed languagesSpring 20137CSE341: Programming Languagesclass A int m() return 0; class B extends A int x; int m() return x; What are generics good for?Some good uses for parametric polymorphism:Types for functions that combi
11、ne other functions:Types for functions that operate over generic collectionsMany other idiomsGeneral point: When types can “be anything” but multiple things need to be “the same type”Spring 20138CSE341: Programming Languagesfun compose (g,h) = fn x = g (h x)(* compose : (b - c) * (a - b) - (a - c) *
12、)val length : a list - intval map : (a - b) - a list - b listval swap : (a * b) - (b * a)Generics in JavaJava generics a bit clumsier syntactically and semantically, but can express the same ideasWithout closures, often need to use (one-method) objectsSee also earlier optional lecture on closures in
13、 Java/CSimple example without higher-order functions (optional):Spring 20139CSE341: Programming Languagesclass Pair T1 x; T2 y; Pair(T1 _x, T2 _y) x = _x; y = _y; Pair swap() return new Pair(y,x); Subtyping is not good for thisUsing subtyping for containers is much more painful for clients Have to d
14、owncast items retrieved from containersDowncasting has run-time costDowncasting can fail: no static check that container holds the type of data you expect(Only gets more painful with higher-order functions like map)Spring 201310CSE341: Programming Languagesclass LamePair Object x; Object y; LamePair
15、(Object _x, Object _y) x=_x; y=_y; LamePair swap() return new LamePair(y,x); / error caught only at run-time:String s = (String)(new LamePair(hi,4).y);What is subtyping good for?Some good uses for subtype polymorphism:Code that “needs a Foo” but fine to have “more than a Foo”Geometry on points works
16、 fine for colored pointsGUI widgets specialize the basic idea of “being on the screen” and “responding to user actions”Spring 201311CSE341: Programming LanguagesAwkward in MLML does not have subtyping, so this simply does not type-check:Cumbersome workaround: have caller pass in getter functions:And
17、 clients still need different getters for points, color-pointsSpring 201312CSE341: Programming Languages(* x:real, y:real - real *)fun distToOrigin (x=x,y=y) = Math.sqrt(x*x + y*y)val five = distToOrigin x=3.0,y=4.0,color=red(* (a - real) * (a - real) * a - real *)fun distToOrigin (getx, gety, v) =
18、Math.sqrt(getx v)*(getx v) + (gety v)*(gety v)Wanting bothCould a language have generics and subtyping?Sure!More interestingly, want to combine them“Any type T1 that is a subtype of T2”Called bounded polymorphismLets you do things naturally you cannot do with generics or subtyping separatelySpring 2
19、01313CSE341: Programming LanguagesExampleMethod that takes a list of points and a circle (center point, radius)Return new list of points in argument list that lie within circleBasic method signature:Java implementation straightforward assuming Point has a distance method:Spring 201314CSE341: Program
20、ming LanguagesList inCircle(List pts, Point center, double r) List result = new ArrayList();for(Point pt : pts) if(pt.distance(center) r) result.add(pt); return result;Subtyping?Would like to use inCircle by passing a List and getting back a ListJava rightly disallows this: While inCircle would “do
21、nothing wrong” its type does not prevent:Returning a list that has a non-color-point in itModifying pts by adding non-color-points to itSpring 201315CSE341: Programming LanguagesList inCircle(List pts, Point center, double r) Generics?We could change the method to beNow the type system allows passin
22、g in a List to get a List returned or a List to get a List returnedBut cannot implement inCircle properly: method body should have no knowledge of type TSpring 201316CSE341: Programming LanguagesList inCircle(List pts, Point center, double r) List inCircle(List pts, Point center, double r) BoundsWhat we w
溫馨提示
- 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 農(nóng)家樂勞動(dòng)合同標(biāo)準(zhǔn)文本
- 個(gè)人店鋪合伙合同標(biāo)準(zhǔn)文本
- 主山租房合同標(biāo)準(zhǔn)文本
- 如何快速播放課件
- 養(yǎng)殖水體出租合同標(biāo)準(zhǔn)文本
- 軍糧大米供貨合同標(biāo)準(zhǔn)文本
- 2025租賃合同印花稅申報(bào)指南
- 入圍框架協(xié)議合同標(biāo)準(zhǔn)文本
- 供蔬菜合同標(biāo)準(zhǔn)文本
- 公司特聘員工合同標(biāo)準(zhǔn)文本
- 電商運(yùn)營(yíng)總監(jiān)工作的崗位職責(zé)與電商運(yùn)營(yíng)經(jīng)理崗位的具體職責(zé)
- 項(xiàng)目部管理人員通訊錄
- GB/T 6892-2023一般工業(yè)用鋁及鋁合金擠壓型材
- 大學(xué)職業(yè)生涯規(guī)劃主題班會(huì)ppt
- 部編版五年級(jí)語文下冊(cè)第三單元課件
- 吊籃施工安全管理培訓(xùn)課件
- 《用戶體驗(yàn)設(shè)計(jì)導(dǎo)論》第14章-用戶體驗(yàn)質(zhì)量的測(cè)試與評(píng)價(jià)課件
- Python數(shù)據(jù)可視化PPT全套完整教學(xué)課件
- 圓的面積(全國(guó)一等獎(jiǎng))
- 汽車燈光系統(tǒng)說課課件(參賽)
- CLSIM100-S24英文版 抗菌藥物敏感性試驗(yàn)執(zhí)行標(biāo)準(zhǔn);第二十四版資料增刊
評(píng)論
0/150
提交評(píng)論