54
Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static Typing; Subtype polymorphism Prof. Dr. Max Mühlhäuser Dr. Guido Rößling

Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Embed Size (px)

Citation preview

Page 1: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Telecooperation/RBG

Technische Universität Darmstadt

Copyrighted material; for TUD student use only

Introduction to Computer Science ITopic 16: Static Typing; Subtype polymorphism

Prof. Dr. Max MühlhäuserDr. Guido Rößling

Page 2: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

What this lecture is about…

• The Magic Triangle of programming-languages

2

secure

easy expressive

Which invariants existin my program?

How easy is it tounderstand a program?

Which ideas can be expresseddirectly in this language?

We already had this consideration:The discussion pro/contra assignments

Page 3: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Values and types• Definition: A type is a set of values that have some

interesting common property– common properties common operations!

• If a value v is an element of a type T, we say that v is of type T

• Example: {0,1,2,…} is a type: the natural numbers

– Example: {1,2,3,4,5,6} is a type: the set of grades in the German school system

– A value can be of many types

• Other types: Symbol, String, …

3

Page 4: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Values and types• Many abstraction mechanisms in programming languages

are based on the abstraction value type

– E.g., we abstract (* 4 4), (* 3 3) to (square 4), (square 3), where square = (lambda (x) (* x x))

– We assume implicitly that x in the function definition is of type number, because * is defined only for this type

• Functions have a type too, which we expressed with contracts– e.g., (lambda (x) (* x x)) has type number number

4

Page 5: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Type Errors

• A type error occurs when a computational entity (e.g., value or function) is used in a manner inconsistent with the concept it represents

– Hardware Errors• illegal instruction fault, illegal memory reference

– Unintended Semantics• e.g., in int_add(3, 4.5), the value 4.5 may be incorrectly

interpreted as an int that is not related to 4.5

5

Page 6: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Type systems

• A type system is a mechanism that assigns a type (or an amount of types) to every value and prevents type errors

6

Example: Scheme prevents the type error by aborting the program

But we do not receive this error message until we execute the program!

> (define x 'hello)> (+ x 5)+: expects type <number> as 1st argument, given: 'hello; other arguments were: 5

Page 7: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Static type systems• With a static type system, we can check the program for type

errors before its execution

– A big advantage, because we notice an error before it is too late

– More reliable than “testing”, because tests can only check the presence, but not the absence, of errors

• Compiled languages often do these type checks during the compilation

• Interpreted languages can also have static type systems

• Example for statically typed language: Java

7

Page 8: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Static type systems• If type errors are recognized first at runtime, we talk about dynamic

typed languages

• If type errors are not recognized at all, we talk about untyped languages– Example: Assembler

• In reality, many PL are statically checked but do not guarantee safety (sometimes called weak checking)

• Some languages have a static type system, which does not recognize all type errors– “good enough”, 80/20 rule

8

Page 9: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Levels of Type Safety

Weak static checking

(Strong) Static checking

Dynamic checking

C, C++, Pascal Java, ML Smalltalk, Scheme, Scripting Languages

9

Page 10: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

class Counter { int n; Counter(int value) { n = value; } //...}

Statically typed languages

• Examples: Java, C++, C#, Haskell, ML

• The type of every variable can be determined at compilation time – Most statically typed languages reach this

goal by requesting explicit type declarations.

10

In Java, it is impossible to define a variable without declaring its type.

Page 11: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Statically typed languages

• Statically typed languages with implicit declarations use given conventions– FORTRAN: variables starting with I, J, K, L, M,

N contain integers

• There are statically typed languages with type inference– Given the following declaration, the ML-Compiler

comes to the conclusion that x is a number.

11

fun square(x) = x * x

Page 12: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Dynamically typed languages

• In dynamically typed languages, the type of a variable gets bound dynamically

• No type declarations are necessary.• Very comfortable! Enables the definition of

flexible functions, for which the type of the arguments does not matter.

• Examples:– Scheme, Smalltalk, Self, Python, etc.

12

Page 13: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Type checking

• Type checking ensures that the operands of an expression are compatible with the operators– Also that a message at an object is a method in the

interface of the object

• Compatible types are either the same types, or can be converted into each other implicitly– Automatic type conversion is called type coercion– See also the discussion about automatic type

conversion in chapter 2.5.2 SICP (V 9)– integer rational real complex

• A type error occurs when applying an operation to an operand of an illegal type.

13

Page 14: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Type checking

• If type bindings are static, type checking can be done statically (during compilation, static type checking).

• If type bindings are dynamic, type checking can only be done at runtime (dynamic type checking).

• In some statically typed languages, some type checks can be done only at runtime, too– More on this later…

14

Page 15: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Static vs. dynamic type checking

15

String x = "hello";x = x * 10;

During compilation:x = x * 10; ^^^^^^* not defined for type String

(define x 'hello)(+ x 1)

At runtime:+: expects type <number> as 1st argument, given: hello; other arguments were: 1

Invalid use of variables are not found by the compiler and cause runtime errors

Page 16: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Static vs. dynamic type checking

16

String s = new String("Hello World"); s.determineLength();

Compile program…

Error in ... (line 2)

karel.jump(); ^^^^^^^^

Method determineLength() not defined for type String

Page 17: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Static vs. dynamic type checking

17

(define (make-counter n) (define (increment) (set! n (+ n 1)) n) (define (dispatch msg) (cond ((eq? msg 'increment) increment) (else (error "undef operation:" msg))) ) dispatch)(define ca (make-counter 1))(ca 'increment)(ca 'decrement)

At runtime:undef operation: decrement

Page 18: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Static typing is conservative• A perfect static type checker would be a type

checker that reports a type error if and only if the type error will actually happen during program execution

• A perfect type checker does not exist!– Follows from certain undecidability results from

theoretical computer science (“Halting problem”)• Hence, static type checkers approximate the

runtime behavior: They are conservative– Meaning they “err on the safe side”– Whenever a type error would occur at runtime, it will be

detected by the type checker– But some programs that are rejected by the type checker

could be executed without a type error

18

Page 19: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Should languages be checked statically?

Arguments in favor of static checking• Economy of execution

– e.g., arithmetic, method dispatch• Economy of compilation

– separate compilation possible• Economy of small-scale development

– can capture a large fraction of routine programming errors better than manual testing, which is incomplete

– provide documentation on source code– use of type checker as development tool, e.g., renaming

a class to detect all references to it• Economy of large-scale development

– teams can negotiate interfaces that are enforced by compiler

– Abstract away from implementation of large-scale components

19

Page 20: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Should languages be checked statically?

Arguments against static checking• source code more verbose

– many obvious declarations• inflexibility

– static checking is conservative– e.g., try this in Java

• Implementing identity function without type casts• The argument of equals(Object other) should have the same

type as the receiver• clone() always returns an instance of the same type as the

receiver• Many mechanisms have been developed to deal with these

problems– type inference, higher-order type systems, ...– But these mechanisms can be very complex

20

A static type checker is a powerful friend, as long as we write programs that are within the boundaries of what the type system can express. If we want to go beyond these boundaries, the type system gets in our way.

Page 21: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Static and dynamic type

• The type of an object is always the class whose instance it is – this type is always bound dynamically to an object.

• Considering variables, we distinguish the static and dynamic type:– The static type of a variable is the type which

gets bound to it with the declaration.• It does not change during the execution.

– The dynamic type at a time t during the execution is the type of the object to which the variable refers at time t.

21

Page 22: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Static and dynamic type

22

Shape shape = null; shape = new Circle(10, 20, 16); shape.draw(canvas); shape = new Rectangle(10, 10, 20, 5); shape.draw(canvas);

In this program, we use one name in different places to refer to two different objects. We call such a variable polymorph.

In the real world, many objects may be called shape, and who is meant depends on the context – just as in the world of graphical objects.

Static type of the variable shape

The dynamic type of the variable shape at this time is Circle

The dynamic type of shape at this time is Rectangle

Page 23: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Static and dynamic type• Is it possible to assign a graphical object of arbitrary

type to an arbitrary variable?– Of course not! That’s what type systems are

about:• A type controls how a name can be used• It delimits the set of values that can be assigned to

a variable … and the operations that can be executed on it

– Only instances of a direct or indirect subclass of its static type can be assigned to a variable.

23

public void main(String[] args) { GOval shape = null; shape = new GRect(10, 10, 20, 5); // ...}

STOP

Page 24: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

The substitution principle

• An object (graphical object) of a subclass can be used everywhere where an object (graphical object) of a super class is expected.This substitutability relation is transitive.

24

• Every object of classes B, C and all of their subclasses can be bound to var (transitivity of the substitutability).

• Every operation declared in A and B can be called on var (on every object stored in var)

• It is not allowed to call an operation on var that is declared in C, but not in A or B.

A

B

C

The declaration B var; implies

Page 25: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

The substitution principle

• An object of a subclass can serve an object of a super class as a representative: – Its structure contains all attributes of an object of

the super class– It can execute all operations that were defined for

objects of the super class

• The opposite is not true! – An object of a super class is not specialized enough

to play the role of the object of a subclass.

25

The declaration B var; does not mean “var is exactly of type B“; but “the behavior of var conforms to B“.

Page 26: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Substitution principle: an analogy

26

• Assume that a customer of a car rental makes a reservation on a four wheeled vehicle to transport small furniture.• It is OK if he gets a van. A van has four wheels.

• But if he ordered a truck, it is not OK to give him any arbitrary four wheeled vehicle.• For example, the cargo area of the van could be too small

Vehicle

TwoWheeler FourWheeler

Motorcycle Bicycle Truck Van

Page 27: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Subtype polymorphism

27

Same code, but different meaningsPOLYMORPHY

Shape shape = null; shape = new Circle(10, 20, 16); shape.draw(canvas); shape = new Rectangle(10, 10, 60, 20); shape.draw(canvas);

Page 28: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Subtype polymorphism

28

• Each graphical object obeys orders according to its programming:

paint(Graphics g);GOval vs. GRect

• This is especially interesting if many graphical objects obtain the same orders, but implement them differently.

Page 29: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Subtype polymorphism once again

29

Now that we know interfaces, we consider static and dynamic types of variables, subtype polymorphism and substitutability together.

For this purpose, we will use the UML class diagram on this slide. It shows a simple type and class hierarchy.

Page 30: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Subtype polymorphism once again

30

Although the model is called “class diagram”, it is actually a type diagram.

Every Java class and interface declares a user defined data type.

The model represents five types: four classes and one interface.

Page 31: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Subtype polymorphism once again

31

Viewed from an implementation independent (thus type oriented) point of view, each of the five rectangles represents a type.

Viewed from the implementation point of view, four of these types are defined by classes and one by an interface.

Page 32: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Implementation hierarchy

32

class Base {  public String m1() {    return "Base.m1()";  }  public String m2(String s) {    return "Base.m2(" + s + ")";  }}

interface IType {  String m2(String s);  String m3();}

class Derived extends Base implements Itype {  public String m1() {    return "Derived.m1()";  }  public String m3() {    return "Derived.m3()";  }}

Page 33: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Implementation hierarchy

33

class Derived2 extends Derived {  public String m2(String s) {    return "Derived2.m2(" + s + ")";  }  public String m4() {    return "Derived2.m4()";  }}

class Separate implements Itype {  public String m1() {    return "Separate.m1()";  }  public String m2( String s ) {    return "Separate.m2(" + s + ")";  }  public String m3() {    return "Separate.m3()";  }}

Page 34: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

References as portholes

34

Derived2 derived2 = new Derived2();

This expression does two things: it• declares the explicit typed

reference variable derived2,• binds derived2 to a newly

created Derived2 object.

The Derived2 reference can be considered as an set of portholes, through which the Derived2 object is viewed.

There is one porthole per operation in the type Derived2. The Derived2 object maps every Derived2 operation to applicable code, as intended in the implementation hierarchy.

Page 35: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

References as portholes

35

Derived2 derived2 = new Derived2();

Example:• The Derived2 object maps

m1() to code that is defined in class Derived.

• Further this code overwrites the implementation of m1() in the class Base.

A Derived2 reference variable can not access the overwritten method m1() in Base. But the implementing code in class Derived can use the implementation in Base via super.m1(). Concerning the reference variable derived2, this code is not visible.

Page 36: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Multiple references to one object

36

Substitutability: We can reference the Derived2 object that is bound to the reference derived2, with every variable of a type T, if Derived2 conforms to T.

The outcome of the type hierarchy is that Derived, Base, and IType are super types of Derived2, thus Derived2 conforms to them.

Because of this, e.g., a Base reference can be bound to the object, referenced by derived2.

Base base = derived2; produces more portholes

Page 37: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Multiple references to one object

37

• The Derived2 object or its operations mappings are not changed.

• If m1() or m2(String) are called on derived2 or base, the same code is executed.

String tmp;

tmp = derived2.m1();    // Derived2 reference     // tmp is "Derived.m1()"

tmp = derived2.m2("Hello”);// tmp is "Derived2.m2(Hello)"

tmp = base.m1();      // Base reference             // tmp is "Derived.m1()"

tmp = base.m2("Hello");        // tmp is "Derived2.m2(Hello)"

Page 38: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Multiple references to one object

• Why do we get identical behavior, despite different references?

• An object does not know who or what calls its methods. – A Derived2 object knows only that it has to obey the

orders, which are given by its implementation hierarchy, when called.

• method dispatch

• These rules constitute that the Derived2-object has to execute the code defined in the class Derived for method m1(), and the code defined in Derived2 for m2(String). – The action executed by the referenced object does not

depend on the type of the reference variable.

38

Page 39: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Multiple references to one object

39

String tmp;// Derived2 reference tmp = derived2.m3(); // tmp is "Derived.m3()"tmp = derived2.m4(); // tmp is "Derived2.m4()"

// Base reference tmp = base.m3();  // Compile-time errortmp = base.m4();  // Compile-time error

• Neither the Derived2 object nor its operation mappings are changed.

• However, the methods m3() and m4() can not be accessed anymore.

Page 40: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Multiple references to one object

40

• The Derived2 object can still accept calls from m3() and m4(). • Type restrictions, which prevent such calls via the Base

reference, appear at compilation time.

• The static type check behaves as a shield, as it allows interactions between objects only by explicitly declared type operations.• The static types of the references define the borders of

object interaction.

• This can be generalized: when a super type reference gets bound to an object, its use gets restricted.

• Why should a developer decide to lose object functionality?

Page 41: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Multiple references to one object

This decision is often unintentional. Assume a reference variable ref is bound to an

object, whose class contains the following method definition:

41

public String poly1(Base base) {  return base.m1();}

The following call is allowed, because the parameter type is conformant:

ref.poly1(derived2); Through the method call, a local Base reference gets

bound to the passed object.

Page 42: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Multiple references to one object

• From the caller’s point of view, who passes the Derived2 object, the binding of a Base reference by the implementer of poly1(Base) amounts to a loss of functionality.

• For the implementer, however, every object passed to poly1(Base) looks like a Base-object.

– The implementer does not care that multiple references can refer to the same object

– In his point of view, the same reference type gets bound to all objects that are passed to the method.

– That these objects possibly are of different type is secondary.

– The implementer expects only that the respective object can map all operations of the type Base to according implementations. 42

Page 43: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

One reference to multiple objects

• Interesting polymorphic behavior appears if a reference variable is bound to multiple objects, as the case may be, of different types. – Strictly speaking, object type means exactly

the type defined by the class of the object.

43

Derived2 derived2 = new Derived2();Derived derived = new Derived();Base base = new Base();

String tmp;tmp = ref.poly1(derived2); // tmp is "Derived.m1()"tmp = ref.poly1(derived);  // tmp is "Derived.m1()"tmp = ref.poly1(base);     // tmp is "Base.m1()"

Page 44: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

One reference to multiple objects

44

• Different objects are viewed through the same porthole:– The porthole defines the mappings which should be

available.– Different objects have different mappings.

Page 45: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

The power of polymorphism

45

• The code of poly1(Base) considers every object through a Base typed lens.

• If a Derived2 object is passed, the method returns a result which was calculated by code in class Derived

• If the classes Base, Derived or Derived2 later get extended, poly1(Base) will accept objects of the new classes and execute the desired code.

• Polymorphism makes it possible that the new classes can be added long after the implementation of poly1(Base).

Page 46: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

The power of polymorphism

• How does that work?

• From the type-oriented point of view, the real implementation code is unimportant.– The most important aspect of the binding of references to

objects is that the type check that takes place at compilation time can guarantee that the referenced object for every operation of the type has an implementation available at runtime.

• Polymorphism liberates the developer from the duty to know implementation details of single objects, and allows instead to make a draft, only from a type oriented point of view.– This is the significant advantage of separating type and

implementation (also called “Separation of interface and implementation").

46

Page 47: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Java interfaces and polymorphism• Java interfaces declare user-defined types

– Java interfaces allow polymorphic behavior by creating a type inheritance structure.

47

public String poly2(IType iType) {  return iType.m3();}

Assume a reference variable ref gets bound to an object, whose class contains the following method:

The following illustrates polymorphic behavior in poly2(IType):Derived2 derived2 = new Derived2();Separate separate = new Separate();

String tmp;tmp = ref.poly2(derived2); // tmp is "Derived.m3()"tmp = ref.poly2(separate); // tmp is "Separate.m3()"

Page 48: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Java interfaces and polymorphism

• Viewed from the type-oriented point of view, there is no difference between the examples of poly2 and poly1.

48

Page 49: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Java interfaces and polymorphism• There is, however, an important difference in

the implementation:– In poly1(Base), the necessary subtype relations

are established by the class inheritance chain Base-Derived-Derived2 and the overwriting of methods leads to the proper mappings to implementation code.

– poly2(IType) shows a completely different behavior. The classes Derived2 and Separate do not share a common implementation hierarchy.

• But instances of these classes create polymorphic

behavior by an IType reference.

49

By the arrangement of objects out of different implementation hierarchies, Java interfaces allow polymorphic behavior even in absence of common implementations or overwritten methods.

Page 50: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Interface and type of an object

• What do we mean with the interface of an object?

• Typically, this describes the set of all public methods that are defined in the class hierarchy of the object– The set of all public

available methods which can be called on the object.

50

In the picture, the interface to the object refers to the layer, called "Derived2 Object”, which mentions all available methods for the Derived2 object.

Page 51: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Interface and type of an object

• This definition of the object interface leads to an implementation centric point of view: – One concentrates on the runtime abilities of an object,

instead of a type-oriented point of view

• To understand polymorphism, however, we have to consider the object from a type oriented point of view of the "Base Reference“ called layer.

• The type of the reference variable dictates an interface to the object. An interface, not the interface. – Driven by type conformity, multiple type-oriented

points of view can be bound to an object.– There is no single specified interface to an object.

51

Page 52: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Interface and type of an object

• Regarding types, the interface to an object is the widest possible type-oriented view on it.– A super type reference, bound to the object, typically

delimits this view.

• The type concept includes the spirit of liberation of object interaction from implementation details in the best way.– Instead of referencing the interface of an object, a type

oriented perspective encourages referencing the reference type bound to the object.

– The reference type dictates the allowed interaction with the object.

• Consider the type if you want to know what an object can do, as opposed to the way how the object does it.

52

Page 53: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Object interface (once more)

• On slide 30, both the Derived2- and the Separate-object have a method m1(). – As we discussed already, the interface of every object

here includes the method m1(). • However, there is no possibility to use these method

m1() polymorphically with these two objects – It is insufficient that every object has a method m1(). – A common type with the operation m1() has to exist

via which one can see the objects. The objects look like they were sharing m1() in their interfaces.

– However, without a common supertype, polymorphism in Java is impossible.

• The reason is that Java has a nominal and not a structural subtyping discipline– Structural: method signatures must „fit“– Nominal: in addition, a subtype relation has to be

declared explicitly (implements/extends clause)

53

Page 54: Telecooperation/RBG Technische Universität Darmstadt Copyrighted material; for TUD student use only Introduction to Computer Science I Topic 16: Static

Dr. G. RößlingProf. Dr. M. Mühlhäuser

RBG / Telekooperation©

Introduction to Computer Science I: T17

Final remarks

• The comprehension of subtype polymorphism requires a change in our thinking towards types instead of implementations.– Types define object groupings and control allowed object

interactions. – The hierarchical structure of type inheritance results in

type relations, which are necessary for reaching polymorphic behavior.

– Types specify which methods an object can execute; implementation specifies how an object reacts on method calls.

– Thus types define responsibilities and classes implement them.

• By a clean separation of type and implementation, both control a “dance of objects": – Types define allowed dancing partners– Implementations define the choreography of the dancing steps.

54