計算機科學(xué)分類programming languages編程語言lec25slides_第1頁
計算機科學(xué)分類programming languages編程語言lec25slides_第2頁
計算機科學(xué)分類programming languages編程語言lec25slides_第3頁
計算機科學(xué)分類programming languages編程語言lec25slides_第4頁
計算機科學(xué)分類programming languages編程語言lec25slides_第5頁
已閱讀5頁,還剩13頁未讀 繼續(xù)免費閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請進行舉報或認(rèn)領(lǐng)

文檔簡介

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等.壓縮文件請下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲空間,僅對用戶上傳內(nèi)容的表現(xiàn)方式做保護處理,對用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時也不承擔(dān)用戶因使用這些下載資源對自己和他人造成任何形式的傷害或損失。

評論

0/150

提交評論