<<

IN 3040 - 2020 1 ) [email protected] ) Pedersen ( Pedersen - and Object Object and , part II [email protected] ’ material by Birger Møller ’ years Programming Languages Orientation – Eyvind W. Axelsen ( Axelsen W. Eyvind previous Types, from from IN3040 adapted Slides Slides 10/29/20 IN 3040 - 2020 2 ? !) - behavior briefly of Today very concepts Generics - inheritance oo II classes Orientation Parametric/ Specialization Multiple alternatives Inner – – – – Type systems ( systems Type Polymorphism ”Advanced” Lecture § § § of and Object Object and )types subclassing (simple) and (simple)and methods parameters contravariance / <> of composite ( I I compatibility compatibility data types data Subtyping Types Types redefined predefined § defined - Subtyping Class Covariance to Type via – – – – – – Classes Abstract From From user

10/29/20 § § § Lecture Types, IN 3040 - 2020 3 . ? things ? ? entail write mean ) and ) and ascribe to to you separate separate text Student two help a when ("INF3110") of are ) (program (program called " + " World" is is concept

Hello syntax the " meaning type systems type : (

to to programs: operation does does and

What

Which System.out.println What

10/29/20 § § § meaning Types Types semantics Remember Repetition IN 3040 - 2020 4 nominal type checking nominaltype : A piece of the program to which to program the pieceof A assign a label.assigna is a type? ? isableto (fields, operations): structural type checking type structural operations): (fields, (e.g. Int32, Person, Stack) Person, Int32, (e.g. What identified - name name structure , and the arithmetic operations on them on operations arithmetic the and integers,

(but don’t worry too much about this now)this about much too worry don’t (but Alternative definition of “type”: “type”: definitionof Alternative system type the By its By its By them 32 32 on operate that methods the and class, Person a of Instances

– – – – – – Does this cover everything a type might be? No.be? might type a everything cover Doesthis

How is a type Howtype isa A of values that have a set of operations incommon operations of set a have valuesthat of set A

10/29/20

§ §

§ Repetition IN 3040 - 2020 5 - user , … } Wed . types to to types classes domain ) types) composite types { Mon, Tue, other application data types, types, data of languages from the predefined of some built WeekDay abstract (in parts parts types procedures enum types , real,... , unions, , reflect , e.g. collections Classification composite that simpletypes - , structs / , composite , simple types (not (not simpletypes , , lists/ , types types

defined defined - -

Records Arrays string enumerations boolean to pointers pointers,

– – – – – – defined Evolution from simple types, via simpletypes, Evolutionfrom User Predefined User Predefined

10/29/20

§ §

§ §

§ Repetition IN 3040 - 2020 6 [Pierce, 2002] [Pierce,

according to the kinds of values they compute” valuesthey kindsof the to according “A is a tractable syntactic method for proving the the proving for method syntactic tractable isa system type “A classifyingby phrases behaviors program certain of absence

– One possibleOne definition

§ What is a type system? IN 3040 - 2020 7 and programs programs [Pierce, 2002] [Pierce, ) predates programming languages, behaviors by classifyingby behaviorsphrases , and not other kinds of type systems type kindsof other not and , program The idea of idea The type systems (or typeand theoryas well has other applications

§

programming languages programming according to the kinds of values they compute” valuesthey kindsof the to according to inrelation systems intype interested are We “A type system is a tractable syntactic method for proving the the proving for method syntactic tractable isa system type “A certain of absence

– – One possibleOne definition

§ What is a type system? IN 3040 - 2020 8 phrases [Pierce, 2002] [Pierce, for proving the the proving for classifying syntactic method method syntactic of values they compute” valuesthey of . runtime This applies to static type systems type static to applies This of track keep and label hand, other the on systems, type Dynamic data at

§ §

language, and assigns labels (types) to them. to assignslabelsand language, (types) according to the kinds the to according inthe terms, or phrases, dealswithsyntactic system type The “A type system is a tractable tractable isa system type “A by behaviors program certain of absence

– – One possibleOne definition

§ What is a type system? IN 3040 - 2020 9 ? proving the the proving [Pierce, 2002] [Pierce, by classifyingby phrases ArrayIndexOutOfBounds ? , 2004] Cardelli [ NullReferenceException But But what constitutes error?an execution There There are a hard type behaviors tolimits ofwhat undesirable system can prove about,things e.g. (non)termination

§ §

occurrence of execution errors during the running of a of running the during errors execution of occurrence program” undesirablebehaviors the prevent isto system type a of purpose fundamental “The according to the kinds of values they compute” valuesthey kindsof the to according certain of absence the prove isto system type the goalof The “A type system is a tractable syntactic method for for method syntactic tractable isa system type “A behaviors program certain of absence

– – – One possibleOne definition

§ What is a type system? IN 3040 - 2020 10 [Pierce, 2002] [Pierce, length of the program should not be tooshould high syntactic method for proving the the proving for method syntactic with regard to polynominal time, time, tractable polynominal Tractable =Tractable In practice, the ofdegree the

§ §

computationally tractable computationally according to the kinds of values they compute” valuesthey kindsof the to according be shouldpreferably system type the goal, its attain to order In “A type system isa system type “A classifyingby phrases behaviors program certain of absence

– – One possibleOne definition

§ What is a type system? IN 3040 - 2020 11 time - betweensafetyand expressivity thatmust be world”languages are somewhere in between, with tension - By a runtime system, or By code inserted by a § § elementsfrom more than one category Thereisa resolvedbythe language/type system designer Most“real Typesare checked runtimeat Typeschecking aissyntactic process compileat Rejectsprograms thatdo not type check before they can run Thereare no types (e.g. everything isjusta bit pattern) youif Or, will, everything has the same single type – – – – – – – Categoriesare not mutually exclusive Dynamicallytyped (or: dynamically checked) Staticallytyped Untyped

§ § § §

type systems type Main categories for language programming for categories Main IN 3040 - 2020 12 Image from JTransformer from JTransformer Image Milner style Milner - Hindley , etc etc ) is typically )created fromis typically the the source using code conformance style”, as in Java, C++, C++, Java, in as style”, - structural abstract syntax nominal

semantics the program the Checks or language to according Thus type checking checking type Thus tree will be declarations of of declarations will be tree annotations type or types, Some of the nodes in the in nodes the of Some Types annotations can be specified explicitly in the source code by the programmer, programmer, the by code source the in explicitly specified be can annotations Types “ALGOL Haskell, ML, in as compiler, the by inferred be can they Or

• • – – – semantics semantics to establish between relationships typesand expressions Uses the language’s the Uses language’s An AST ( grammar language’s Types are assigned to are Types elements syntactical ofassigned a program (prior toit) running Static type systems • § § IN 3040 - 2020 13 between flexibility and typeand flexibility between anonymous anonymous – tradeoffs references, runtime contract checking - user conservative in C# in Ocaml etc constructs in Ada in constructs in in > > license to kill [the type system]” type kill [the to license “ stackoverflow.com – type error type error valid code valid code Obj.magic JavaScript, ML, e.g. languages, most in Interfaces Function Foreign Java, Python, Unchecked_ unsafe { … } < < § § § § E.g. covariant array null conversions, hatches to Escape circumvent the type system: else They cannot They (in prove general) the ofpresence errors, the ofonly absence certain behaviors bad are They therefore reject to “correct”bound potentially programs to true > ) that always evaluates runtime condition if( < complex – – – – Mainstream languages typically concede to concede typically Mainstream languages safety Static Static type systems are always

§ § Static type systems [cont.] IN 3040 - 2020 14 at runtime at * bound on correctness, while (static) while correctness, on bound find the errors that a compilerwoulda that errors the find bound , otherwise, anything could happen could anything otherwise, , upper may lower lower safe incorrect operations will operations caught beincorrect - runtime the receiver supports the requested operation, operation, requested the supports receiver the type systems find a a find systems type A test suite can find an an find can suite test A * if the language is language the if *

§ §

Extensive testing/TDDExtensive found haveotherwise But may indeed end up running many faulty ones faulty many runningup indeedend may But Errors due to type to due Errors As longas As isfine everything

– – – – Never need to reject a correct program correct a reject to need Never

Type checks at at checks Type

§

§ Dynamically typed languages typed Dynamically IN 3040 - 2020 15 ()) ); args (); , name ( App.User.IsAuthorized { && ) ”) args get , (“ name ( MessageNotUnderstoodException object protocols with sophisticated behaviorwithsophisticated protocols object - OtherClass..Invoke new throw name.startsWith return ( Responding to method calls or not depending on runtime runtime on depending not or calls method to Responding e.g.: environment, methodMissing § if else Create and cache new methods from business rules defined by definedbusiness rules from newmethods cache and Create DSLinternalin an e.g. users, Effortlessly create proxies at runtime at proxies create Effortlessly Can have meta Canhave

} def – – – present?) correctly type the program the type correctly present?) Freedom of expression where static type system cannot (at (at cannot system type static whereexpression of Freedom

Dynamically typed languages [cont.] languages typed Dynamically § IN 3040 - 2020 16 2009] Vitek [ ; { null => (); = () ); = !" mom FancyThing "Hi ( new log doSomething someOtherMethod = . . .

console myObject } myObject myObject Add or remove methods or fields, swap out classes, etc. classes, swapout fields, or methods remove or Add

Used a great deal by e.g. Flickr, Facebook and Gmail andFacebook Flickr, e.g. dealby great Useda Classes and objects can be adapted at runtime at adapted be can Classesobjects and

10/29/20 §

§ Dynamically typed languages [cont.] languages typed Dynamically IN 3040 - 2020 17 .” byatype addressed by a type theory is that that is theory type a by caused is to ensureisto thatprograms have meaning. for richer type systems results from this tension this from results systems type richer for “The fundamental problem fundamental “The : quest [as quoted by Pierce 2002, p 208] p Pierce2002, by quoted [as The The [akatype system] Mannasse them. The fundamental problem problem fundamental The to ascribedmeanings have not may programs meaningful theory Mark IN 3040 - 2020 18 (author, blogger,) (author, . ”

Grossbart

Zack –

Static typing Static isgreat because keepsit

outyourof way Dynamictyping greatis because getsit yououttrouble of “ Words of wisdom? IN 3040 - 2020 19 . . be can for for be . that can polymorphism name . usable to as subtype a same same polymorphism [https://wiki.haskell.org/Polymorphism] of generics the just just referred with called arities instance called simply : an ) expected methods typically often / typically is is is when the type of a value contains one or more more or one contains value a of type the when this this : " a single single a , , subtyping this ( functions , – : overloading a supertype is supertype a different typesdifferent , so that the value may adopt any type that results from results that type any adopt may value the that so , of called communities communities where polymorphism communities polymorphism to different parameter types and and types parameter different to polymorphism In OOP In OOP In FP Typically – – – – substituted Subtype substituting those variables with concrete types” types” concrete with variables those substituting Parametric Parametric variables type Ad hoc hoc Ad applied

10/29/20 § § § instances Polymorphism IN 3040 - 2020 20 of really , is > > String String independently , expressiveness List< own of List< its our on ? construct isin degrees type type safe? type type be? types ? can polymorphism analyzed T of it it generic whatever be used to to used be the what about offer different different offer type be type is that , etc. , can , or types types or , said subtype ? be extent cases? generic constrain sure be - parametric / can about languages the we we strings List List use which

constructors any What To Can Can Can only What E.g. E.g. List

– – – – – – –

Different Different Type

10/29/20 §

§ Generics IN 3040 - 2020 21 no on provide constraints parameters templates ) C++ C++ for support j++ < 1; - [j]); ++) [] ) { ]) i i arr [ arr 1; ], - arr i [ < T> arr

for

Usage, meaning and implementation of of implementation andmeaning Usage,

} void template

What parts of the implementation depend on what property of T? of property what on depend implementation the of parts What C++ polymorphic sort function polymorphicsort C++

10/29/20 §

§ Constraining type parameters type Constraining IN 3040 - 2020 22 >(); () next Integer < (). () list next (); generics LinkedList (). generic new (0)); (0)); with = with LinkedList myIntList.iterator and and ) Integer time Integer new = myIntList new new ( Integer this ( > myIntList.iterator without

x = x = ( same,

Integer myIntList < the

Integer myIntList.add // List // take an integer out from the list // take an integer Integer myIntList.add List the list an integer to // add // create new list // create

10/29/20 Java lists lists Java IN 3040 - 2020 23 > ? Double

String Object > ?

Number Number

Object List< < Integer of

List >(); of subtype (1,2); > String subtype < > time - Integer attempts to assign assign to attempts error .asList an Object to a String a to Object an String < List< compile ; List ArrayList è Arrays ints è = new = ()); (0); ints Number nums Object > of > ls = > lo = ls; Object ls.get of > (3.14); new s = ( subtype String Object time Integer Number subtype < < - < < error lo.add String List List List nums.add List Integer String

compile

10/29/20 §

§ Generics and subtyping IN 3040 - 2020 24 [ ]? Object subtyping of // ??? [10]; and and ; subtype // !!! [ ] String (); Arrays String ; ; ? new " myStrings è = = Object this Hello new " "World!" in Java and/or C#! and/or Java in Object out of about it myObjects [3] = myStrings [0] = [1] = Try

[] []

subtype what

10/29/20 myObjects Object myStrings myStrings String String But IN 3040 - 2020 25 > > of type type of any any subtype I a - subtype not Collection< isa Collection Collection< is Collection : > c){ Wildcards - collection Object c) { c) { < c) { any ()); of (); i.next (); k++) (); k++) ( (e); (e); Collection Collection Collection elements elements ( ( ( the c.size polymorhpism print c.iterator e : c) e : c) to = .out.println i .out.println .out.println code Object Object ( ( (k = 0; k < (k = 0; printCollection printCollection System printCollection System System

for for for Iterator

} void } void } void 10/29/20

Goal: Write Write Goal: Unbounded IN 3040 - 2020 26 Double Rectangle

à Number Shape shape

of II Circle Integer - );} kind

any this of ( a list a Shape { s.draw Wildcards draw Shape { Shape { - to code extends draw(Canvas c); draw(Canvas Shape { Shape extends Write draw(Shape s) { draw(Shape s) draw(Canvas c) { ... } c) { ... draw(Canvas height; x, y, width, { ... } draw(Canvas c) x, y, radius; Canvas { Rectangle Circle

polymorhpism int int

public void private public void public void public private private public abstract void abstract public

} public class }

public class } public class public } public abstract class abstract public

10/29/20 Bounded IN 3040 - 2020 27 or e.g. a a being draw S rectangles being of S every III Cannot list circles - for > every for > shapes) { > shapes) Shape T > Shape Wildcards T - > shapes) { { > shapes) Shape extends extends extends Shape

Shape Shape

( (

s.draw s.draw subtype subtype List a List

for for

} public void public void } public void public // in class Canvas: class // in

10/30/20 §

§ Bounded IN 3040 - 2020 28 c) { c) { why? – Collection Collection [] a, [] a, (T[] a, Object ( why? – // compile time error // compile fromArrayToColl // works o: a) fromArrayToColl void (o); (o); Object (T o: a) (T o: a) ( c.add c.add

for for

} static } static void void static

10/29/20 Generic methods IN 3040 - 2020 29 ) { copy( src > void T > collections T ){ src copy( extends > Copy S ? extends < < - ) ) S void List , > List src src (s); (s); T T , < < , s : s : dest dest S T ( ( methods > > dest.add dest.add T T < < } for } for Collections { Collections { Collections } } List or: List

public static public static public static

-- } class } class

10/29/20 Generic IN 3040 - 2020 30 ){ snk …? sink.flush Sink , coll Illegal call Illegal to disk using to disk to sinks to coll //? // can it write strings // can it write Collection ( write – , s); cs // a sink that can write any object // a sink that = ... ; ( writeAll cs > ) { // return last element written // return last T // flush might for instance write stuff to disk write stuff might for instance // flush writeAll coll (last); writes everything in writes everything > s = ...; String = parameters < last; Sink { Sink str (T t : Object

< last = t; snk.flush

return } writeAll T last; for flush(T t); flush(T

10/29/20 Generic Collection String ... Sink } // public static } interface IN 3040 - 2020 31 type: type: Object String T which is which T call ok, but but ok, call wrong return return wrong which is now isnow which Yes: returns T T returns Yes: ){ snk T> ){ //? //? super ( ( Sink , Sink cs cs ( ( ; writeAll , writeAll cs coll extends T T writeAll writeAll Collection Sink s; Sink IN 3040 - 2020 32 that of the subtype in in print ? ? of behavioral a behavior superclass the the Is Is subclasses in specification print() TrainReservation train waggon seat print() behaviour Reservation date customer of print()

FlightReservation flight seat

10/29/20 Subtyping to

IN 3040 - 2020 33 ” the thing on of ”right ”right depend the FlightReservation do We developer the super style super the Reservation { – extends for behaviour behaviour for ’ .print(); print { super and Seat // print Flight print() { print() FlightReservation FlightReservation Reservation { Reservation void flight . . .; seat . . .; } // print date and Customer // print }

date . . . ; date . . . . . ; customer void

} class }

class Subtyping

10/29/20 ’ IN 3040 - 2020 34 No, still only still No,only compatibility, structural of interms structure but statements, of sequence signature inadditionto of types of (number parameters)! Does the inner style givestyle inner Doesthe behavioralcompatibility? § § the inner style inner the – { extended ; Reservation { print ; // print flight and seat // print flight inner print Date and Customer and Customer print Date print() { print() void FlightReservation seat . . .; flight . . .; // inner Reservation { Reservation } extends } date . . . ; customer . . . ; . ; customer date . . void

} class } class

10/29/20 Subtyping for behaviour IN 3040 - 2020 35 , deque (ep) , often , often ended ended queue - Stack dequeue A A double ( to abbreviated deck) is an pronounced abstract that a queue, for generalizes elements can be which to added or removed front the either from (head) or back (tail) e; ep) { push():: insert_front pop():: delete_front dp.insert_rear Element Element s; , (ep); Dequeue dp delete_front() delete_rear() insert_front() insert_rear() Stack d; Dequeue f( Queue dp.insert_front insert_front() delete_rear() Dequeue void } ... f(s, e) = Stack Queue Dequeue Subtyping

insert_rear() delete_front() delete_rear() insert_front() push() pop() delete() insert()

10/29/20 subclassing?? IN 3040 - 2020 36 A context where it isit where context A stack a as used it that sure be cannot stack. a like behaves Dequeue can take take can Dequeue a both of place the Stack a and Queue different (via references). Stack push() pop() Dequeue delete_front():: pop delete_rear() insert_front():: push insert_front():: insert_rear() Queue

insert_front() delete_rear()

10/29/20 The opposite any better?anyopposite The IN 3040 - 2020 37 new extend for to new , and L with want J figures properties figures We this float a; float b; float Ellipse new Circle().color= …; …; Circle().color= new K extension float width; float float height; float ; Rectangle ? descr and and … - area color - - Figure String String FigureX

float r; float Circle

10/29/20 Inheritance IN 3040 - 2020 38 : but ) variables variables of for simple simple for kind overrides description ? («Diamond problem») complexity problem ( with two figure the from Difficult Runtime Complex problem One or - - Solves - - RectangleX float width; float float height; float Rectangle ; descr … - area color - - Figure FigureX String String float r; float Circle

CircleX

10/29/20 Multiple inheritance Multiple IN 3040 - 2020 40 ) ) of for kind typically hierarchy complexity problem ( the : Runtime Runtime ( safe type Not Complex problem? simple - - Solves but - RectangleX float width; float float height; float Rectangle ; descr … - area color - - Figure FigureX String String float r; float Circle CircleX

Figures FiguresX

10/29/20 Virtual classes IN 3040 - 2020 41 ? , the to defined Kitchen, Bedroom // ? ? , belong ; are they apartment Where Bathroom FamiliyRoom Do (); (); ? () (); (); (); (); Bathroom (); ... Address Bedroom = Kitchen new otherAppartment.theKitchen new = new new paint = . = = = (); (); Encapsulation / ; theFamilyRoom theKitchen theKitchen theBathroom . . theAddress theKitchen theBedroom owner FamilyRoom Apartment { Apartment new

Address Person . . . FamilyRoom Bedroom Bathroom Kitchen

10/29/20 Composition myApartment myApartment } class IN 3040 - 2020 42 ; thatOtherKitchen = Apartment(); new = myApartment.kitchen myApartment 10/29/20 IN 3040 - 2020 43 ...} (); (); (); : height (); {... ApartmentBathroom ApartmentBathroom (); (); () Bathroom FamilyRoom new new = = new Address Bedroom = extends this specific Apartment this specific new new = = = new Kitchen(); = new Kitchen(); bathroom1 bathroom2 locally defined classes - ; ; theFamilyRoom theAddress theBedroom theKitchen owner height ApartmentBathroom Apartment { Apartment

Address Bedroom Person . . . FamilyRoom ApartmentBathroom ApartmentBathroom // then use it // then with another Apartment’s rooms: // can’t be mixed class // define inner class // define the height of // reuse Kitchen Height

10/29/20 Inner classes } class IN 3040 - 2020 44 { else < Bathroom Apartment { Apartment { Apartment somewhere PinkBathroom PinkBathroom :: :: extends extends defined ApartmentBathroom syntax ahead) syntax up - PinkBathroom ApartmentBathroom ApartmentBathroom ... More fancy stuff here ...... More fancy VeryFancyApartment // SpecialApartment Apartment { Apartment } class class virtual class virtual ...

} class } class }; class 10/29/20

(warning: made Virtual classes IN 3040 - 2020 45 Anonymous class ); event) { ); >() { "Hello World!" ( ActionEvent (); ActionEvent < Button handle( ( .out.println new = World'" ("Say 'Hello System btn EventHandler } public void

} new

... ); btn.setOnAction Button btn.setText ... anonymous inner classes inner anonymous

10/29/20

- Singular objects (singleton class) IN 3040 - 2020 46 Anonymous class ) { someone someone); + name); new = String String ); ( ( ; "Hallo " ( { () { "Verden" ( "Verden" greetSomeone = greet greet(); greetSomeone .out.println () { HelloWorld void norwegianGreeting name void greetSomeone name = someone; System } } public String public public void void public public void HelloWorld } interface }; HelloWorld 10/29/20 IN 3040 - 2020 47 { p); Anonymous class Person CheckPerson test( Functional interface Functional .Sex.MALE boolean } interface tester) { tester) p) { Person ( () == () >= 18 () <= 25; Person (); CheckPerson { (p)) test( p.getAge p.getAge printPersons () { p.getGender && && p : roster) { roster) p : boolean > roster, > roster, ( tester.test p.printPerson ( return Person } ( if } Person public CheckPerson < } } for roster, new List ); printPersons } public static void static public 10/30/20 IN 3040 - 2020 48 { p); Person CheckPerson test( Functional interface Functional boolean } interface tester) { tester) implements ( (); CheckPerson { (p)) printPersons p : roster) { roster) p : > > roster, > roster, - tester.test p.printPerson ( Person ( if } && p.getAge() >= 18 && p.getAge() >= 25 && p.getAge() <= p.getGender() == Person.Sex.MALE p.getGender() == Person < } for List roster, (Person p) } public static void static public ); printPersons( 10/30/20 IN 3040 - 2020 49 interfaces ? safety guarantees vs functional not as simple or intuitivesimple or as not semantic no expression – of ? , singletonsand , contravariance !) alternatives? – and encapsulation class - freedom behavior briefly revisited – of and think concepts inner very Generics and co and OO inheritance might dynamic topics classes / one

Anonymous Specialization Multiple Inner as Parametric/ Subtyping Static

– – – – – – – ”Advanced” ”Advanced”

Polymorphism Type systems ( systems Type

10/29/20

§ §

§ Today’s IN 3040 - 2020 50 allowed material material written and printed , all , all hours 3 – ! 3 2 summaries November November up! Volker and with exam Repetition Home

10/29/20 § § § Coming