1 / 161

Typing, Inheritance and CATCALL

Typing, Inheritance and CATCALL. 类型,继承以及 CATCALL 问题. 摘要. 类型 继承及其它 Deferred Class 单继承与多继承 协变与反变. 类型. 概念 (值集,操作集) 反映这些值的同质性(意义,目的) 起因 编译技术 作用 Safety Optimization Documentation Abstraction (and Modularity). 关于程序设计语言的类型系统. Typing Type checking

Télécharger la présentation

Typing, Inheritance and CATCALL

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Typing, Inheritance and CATCALL 类型,继承以及CATCALL问题 Institute of Computer Software Nanjing University

  2. 摘要 • 类型 • 继承及其它 • Deferred Class • 单继承与多继承 • 协变与反变 Institute of Computer Software Nanjing University

  3. 类型 • 概念 • (值集,操作集) • 反映这些值的同质性(意义,目的) • 起因 • 编译技术 • 作用 • Safety • Optimization • Documentation • Abstraction (and Modularity) Institute of Computer Software Nanjing University

  4. 关于程序设计语言的类型系统 • Typing • Type checking • The process of verifying and enforcing the constraints of types • Static vs. Dynamic • “Strong” vs. weak • Weak typing means that a language will implicitly convert (or cast) types when used. • Strong: Safe, Static, strong grantees … Institute of Computer Software Nanjing University

  5. 关于程序设计语言的类型系统 • 关于范型 • Java 枚举类型 • Ref: http://www.javaeye.com/a/6556.html Enum<E extends Enum<E>> Institute of Computer Software Nanjing University

  6. Enum • 用法 • 实质 Institute of Computer Software Nanjing University

  7. Enum<E extends Enum<E>> • 回忆:List<T>, List<String>, List<Object> • 一般的 Foo<T> • 回忆:java.lang.class -> java.lang.class<T> Institute of Computer Software Nanjing University

  8. Enum<E extends Enum<E>> • subClassAwareness • public final Class<E> getDeclaringClass() • 返回与此枚举常量的枚举类型相对应的 Class 对象。 • public final int compareTo(E o) • 比较此枚举与指定对象的顺序。 • public static <T extends Enum<T>> T valueOf(Class<T> enumType, String name) • 返回带指定名称的指定枚举类型的枚举常量。 Institute of Computer Software Nanjing University

  9. 继承与类型 • 子类型 • 可替换性:Let q(x) be a property provable about objects x of type T. Then q(y) should be true for objects y of type S where S is a subtype of T. (Liskov substitution principle) • 对于面向对象的计算来说 • 子类型对象须能接收所有父类型对象能接收的消息 Institute of Computer Software Nanjing University

  10. 继承与类型 • Are Cows Animals? -By David L. Shang class Animal proc eat (food: AnyFood); end; ---------------------------------------------------------- class Cow is Animal proc eat (food: PlantFood); end; Institute of Computer Software Nanjing University

  11. 继承及其它 • 何谓继承? • 特征(方法、成员函数)重定义 • 多态与动态绑定 • Inheritance and Design by Contract • 继承 与 泛型 • Assignment attempt Institute of Computer Software Nanjing University

  12. 何谓继承? • Principle: Describe a new class not from scratch but as extension or specialization of one existing class — or several in the case of MULTIPLE inheritance. • From the module viewpoint: if B inherits from A, all the services of A are potentially available in B (possibly with a different implementation). • From the type viewpoint: inheritance is the ‘‘is-plus-but-except’’ relation. If B inherits from A, whenever an instance of A is required, an instance of B will be acceptable.

  13. Terminology • Parent, Heir • Ancestor, Descendant • The ancestors of B are B itself and the ancestors of its parents. • Proper ancestor, Proper descendant • Direct instance, Instance • The instances of A are the direct instances of its descendants. • (Other terminology: subclass, superclass, base class) feature A feature B

  14. Example hierarchy extent* display* * deferred + effective ++ redefined barycenter* * rotate … FIGURE … * * OPEN_ FIGURE CLOSED_ FIGURE perimeter* perimeter+ perimeter+ + + SEGMENT POLYLINE POLYGON ELLIPSE diagonal perimeter++ ... ... side1 TRIANGLE RECTANGLE side2 CIRCLE perimeter++ perimeter++ SQUARE

  15. 子类对父类的扩展与特化 • 继承表达的是一种分类演绎的认识方法 • “To program is to understand.” • 特化:包含范围变小,行为特殊化 • 扩展:增加新的操作 • 重定义:改变行为 Institute of Computer Software Nanjing University

  16. Redefinition classPOLYGON create make feature vertices: ARRAY [POINT] vertices_count: INTEGER perimeter: REALis -- Perimeter length do from...until...loop Result :=Result + (vertices @ i).distance (vertices @ (i + 1)) ... endend invariant vertices_count >= 3 vertices_count = vertices.countend vertices @ i vertices @ (i + 1)

  17. Redefinition (cont’d) classRECTANGLEinherit POLYGON redefine perimeter endcreate make featurediagonal, side1, side2: REAL perimeter: REALis -- Perimeter length do Result := 2 *(side1 + side2) end invariantvertices_count = 4end side2 side1

  18. Inheritance, typing and polymorphism • Assume: p: POLYGON; r: RECTANGLE; t: TRIANGLE; x: REAL  • Permitted: x := p.perimeter x := r.perimeter x := r.diagonal p := r • NOT permitted: x := p.diagonal (even just after p := r  !) r := p 注意理解引用:运行时刻实体 p (POLYGON) r (RECTANGLE)

  19. Dynamic binding • What is the effect of the following (assuming some_test true)? ifsome_testthen p := r else p := t end x := p.perimeter • Redefinition: A class may change an inherited feature, as with RECTANGLE redefining perimeter. • Polymorphism: p may have different forms at run-time. • Dynamic binding: Effect of p.perimeter depends on run-time form of p.

  20. The meaning of inheritance • The type perspective: • Automatic adaptation of operations to the dynamic form of their targets (extendibility):Representation independence. • Factoring out reusable operations: Commonality. • The module perspective (reusability): • Open-closed modules • Modularity • The Single Choice Principle

  21. The traditional architecture display (f: FIGURE) is do if‘‘f is a CIRCLE’’then ... elseif‘‘f is a POLYGON’’then ... end end and similarly for all other routines!

  22. Applying the Single Choice Principle f: FIGURE c: CIRCLE p: POLYGON ... createc.make (...) createp.make (...) ... if ... then f := c else f := p end ... f.move (...) f.rotate (...) f.display (...) ...

  23. The Open-Closed Principle B A C E D F A’ H I G

  24. The dangers of static binding createa.make (…) • For every creation procedure cp: {precp} docp {postcp and INV} • For every exported routine r: {INV and prer} dor {INV and postr} • The worst possible erroneous run-time situation in object-oriented software development: • Producing an object that does not satisfy the invariant of its class. S1 a.f (…) S2 a.g (…) S3 a.f (…) S4

  25. The dangers of static binding (cont’d) • {INVA} dorA {INVA} • {INVB} dorB {INVB} • Consider a call of the form a1.r where a1 is polymorphic: • No guarantee on the effect of dorA on an instance of B! rA A rB++ B

  26. A concrete example w: WINDOW b: BUTTON createb w:= b w.display display WINDOW display++ BUTTON

  27. Using original version of redefined feature classBUTTONinherit WINDOWredefine display end feature displayis doPrecursordisplay_border display_labelend display_labelis do ... end display_borderis do ... end end

  28. Use of Precursor • Not necessarily the first feature statement. • May have arguments. classBinherit Aredefine my_feature end feature my_feature (args: SOME_TYPE) is do-- Something here Precursor (args) -- Something else here end end my_feature A my_feature++ B

  29. Typing vs. binding • What do we know about the feature to be called? • Static typing: At least one • Dynamic binding: The right one • Example: my_aircraft.lower_landing_gear

  30. Example hierarchy * deferred * + effected AIRCRAFT ++ redefined * * PLANE COPTER lower_landing_gear* BOEING AIRBUS lower_landing_gear+ A_320 B_737 B_747 lower_landing_gear++ B_747_400

  31. 动态绑定 • 回顾 C++ 和 Java 的绑定机制 • C++的绑定规则 • 用户指定 • 缺省静态 • 优点?缺点? Institute of Computer Software Nanjing University

  32. 泛型与继承 Abstraction SET_OF_BOOKS Type parameterization Type parameterization LIST_OF_ LIST_OF_PEOPLE LIST_OF_BOOKS JOURNALS LINKED_LIST_OF_BOOKS Specialization

  33. Genericity + Inheritance 1: Polymorphic data structures classSTACK [G] feature ... item: Gis ... put (x: G) is ... end fs: STACK [FIGURE] r: RECTANGLE s: SQUARE t: TRIANGLE p: POLYGON ... fs.put (p); fs.put (t); fs.put (s); fs.put (r)fs.item.display fs (RECTANGLE) (SQUARE) (TRIANGLE) (POLYGON)

  34. Example hierarchy extent* display* * deferred + effective ++ redefined barycenter* * rotate … FIGURE … * * OPEN_ FIGURE CLOSED_ FIGURE perimeter* perimeter+ perimeter+ + + SEGMENT POLYLINE POLYGON ELLIPSE diagonal perimeter++ ... ... side1 TRIANGLE RECTANGLE side2 CIRCLE perimeter++ perimeter++ SQUARE

  35. Genericity + Inheritance 2: Constrained genericity classVECTOR [G -> NUMERIC] feature infix "+" (other: VECTOR [G]): VECTOR [G] is -- Sum of current vector and other require lower = other.lower upper = other.upper local a, b, c: G do ... See next ... end ... Other features ... end

  36. Constrained genericity (cont’d) • The body of infix "+": createResult.make (lower, upper) from i := lower until i > upper loop a := item (i) b := other.item (i) c := a + b-- Requires a “+” operation on G! Result.put (c, i) i := i + 1 end

  37. Constrained genericity (cont’d) • The body of infix "+": createResult.make (lower, upper) from i := lower until i > upper loop a := item (i) b := other.item (i) c := a + b-- Requires a “+” operation on G! Result.put (c, i) i := i + 1 end

  38. The solution • Declare class VECTOR as classVECTOR [G –> NUMERIC] feature ... The rest as before ... end • Class NUMERIC (from the Kernel Library) provides features infix "+", infix "*" and so on.

  39. Improving the solution • Make VECTOR itself a descendant of NUMERIC, effecting the corresponding features: classVECTOR [G –> NUMERIC] inherit NUMERIC feature ... The rest as before, including infix "+"... end • Then it is possible to define e.g. v: VECTOR [VECTOR [VECTOR [INTEGER]]]

  40. Forcing a type: the problem fs.store ("FILE_NAME") ... -- Two years later: fs.retrieve ("FILE_NAME")x := fs.item-- [1] print (x.diagonal) -- [2] But: • If x is declared of type RECTANGLE, [1] is invalid. • If x is declared of type FIGURE, [2] is invalid.

  41. Assignment attempt f: FIGURE r: RECTANGLE ... fs.retrieve ("FILE_NAME") f := fs.item r ?= f ifr /= Voidthenprint (r.diagonal)elseprint ("Too bad.")end

  42. Assignment attempt (cont’d) x ?= y with x: A • If y is attached to an object whose type conforms to A, perform normal reference assignment. • Otherwise, make x void.

  43. 延迟类 • 为什么要延迟类? • 从分析到设计到实现的平滑过渡 • 抽象,复用 • Factoring out the commonalities. Institute of Computer Software Nanjing University

  44. The need for deferred classes • In the scheme seen earlier: f: FIGURE; c: CIRCLE; p: POLYGON ... createc.make (...); createp.make (...) ... if ... then f := c else f := p end ... f.move (...); f.rotate (...); f.display (...); ... • How do we ensure that a call such as f.move (...) is valid even though there is no way to implement a general-purpose feature move for class FIGURE?

  45. Deferred classes deferred classFIGUREfeature move (v: VECTOR) is deferred end rotate (a: ANGLE; p: POINT) is deferred end ... display, hide, ... end Not permitted: createf ...

  46. Example hierarchy extent* display* barycenter* * rotate* … FIGURE … * * OPEN_ FIGURE CLOSED_ FIGURE perimeter* perimeter+ perimeter+ SEGMENT POLYLINE POLYGON ELLIPSE diagonal perimeter++ ... ... TRIANGLE RECTANGLE CIRCLE perimeter++ perimeter++ SQUARE

  47. Deferred classes and features • A feature is either deferred or effective. • To effect a inherited feature (deferred in the parent) is to make it effective. No need for redefine clause. • Like a feature, a class is either deferred or effective. • A class is deferred if it has at least one deferred feature (possibly coming from an ancestor) that it does not effect. It is effective otherwise. • A deferred class may not be instantiated. • BUT: A deferred class may have assertions (in particular, a deferred routine may have a precondition and a postcondition, and the class may have a class invariant).

  48. Deferred classes • Compare with Ada-Modula 2-Java interface/body separation: • May contain both deferred and non-deferred elements. • More than one implementation is possible. • Formal semantic specification (assertions).

  49. Table variants * TABLE * SEQUENTIAL_TABLE + + + ARRAY_TABLE LINKED_TABLE FILE_ TABLE

  50. Don’t call us, we’ll call you deferred classSEQUENTIAL_TABLE [G] inherit TABLE [G] feature has (x: G): BOOLEANis-- Doesxappear in table?do from start until afteror elseequal (item, x) loopforthendResult := notafterend

More Related