计算机科学分类programming languages编程语言lec25slides_第1页
计算机科学分类programming languages编程语言lec25slides_第2页
计算机科学分类programming languages编程语言lec25slides_第3页
计算机科学分类programming languages编程语言lec25slides_第4页
计算机科学分类programming languages编程语言lec25slides_第5页
已阅读5页,还剩13页未读, 继续免费阅读

付费下载

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

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. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论