Administrivia

G Assignments; reducing from 5 to 4 – #2 – due 2/11 (on OO) CSE583: Programming – #3 – due 2/25 (on logic/constraint) Languages – #4 – due 3/10 (on domain-specific, visual languages,etc.) David Notkin G More paper topics listed 1 February 2000 G Returning assignment #1 [email protected] G http://www.cs.washington.edu/education/courses/583 First term paper back next Tuesday

University of Washington • CSE583 • D. Notkin © 2000 2

Object oriented programming Lecture schedule languages G Tonight and next week (2/1 & 2/8): OO G Basic background and introduction G Following two weeks (2/15 & 2/22): logic – A number of you have surely done more OO programming than me and constraint – Definitely comment early and often! G Next to last week (2/29): visual G A deeper look at programming, literate programming – types, multiple inheritance, etc. G Last week (3/7): domain-specific G Quick looks at a few classic and languages (me or Tom Ball) interesting languages

University of Washington • CSE583 • D. Notkin © 2000 3 University of Washington • CSE583 • D. Notkin © 2000 4

A few OO languages Object Oriented

G Simula-67: where it all started G OO programming G Smalltalk-80: popularized OO G OO design gOOd’s G OO modeling G C++: OO for the hacking masses middle name G OO analysis G Java: OO for the web and ??? G OO databases G CLOS: Powerful OO with Lisp G ... G Others? Yeah, lots

University of Washington • CSE583 • D. Notkin © 2000 5 University of Washington • CSE583 • D. Notkin © 2000 6

1 Dimensions of OO Primary focus in OO has three key thrusts this course G design G Abstract data types (ADTs) – What features are there, and why? – A way to structure programs G Programming language implementation G Inheritance – Are these features implemented with – A way to exploit the relationships between sufficient efficiency? ADTs G Software engineering G Dynamic binding – Do these language features help improve – Run-time selection of appropriate software quality or reduce costs? implementation

University of Washington • CSE583 • D. Notkin © 2000 7 University of Washington • CSE583 • D. Notkin © 2000 8

Anything else central to OO? Abstract data types

G Or any of these G An instance of Parnas’ information hiding three that aren’t principle central to OO? – How to choose among alternative modularizations – Identify aspects of a program that are likely to change, and those that are likely to be stable – Capture the stable parts in interfaces, and the likely to change parts in implementations – (There’s a more to it)

University of Washington • CSE583 • D. Notkin © 2000 9 University of Washington • CSE583 • D. Notkin © 2000 10

Information hiding ADTs

ClientClient #1#1 ClientClient #2#2 ClientClient #3#3 G The changeable part of the program is identified to be – the representation of the data and ImplementationImplementation – the implementation of the operations G Clients cannot rely on knowledge of the G The is the stable part implementation, just it’s specification – The “signature” is the syntactic definition of G The implementation can change without the interface affecting the clients – Semantics are usually given informally

University of Washington • CSE583 • D. Notkin © 2000 11 University of Washington • CSE583 • D. Notkin © 2000 12

2 Aside: any weaknesses of ADTs information hiding? G The representation and the operations are G If you took 584 packaged together from me, you must – The representation and implementation remain silent :-) details are encapsulated and hidden from clients G An ADT is a of module, but one that G Weakness of (usually) allows clients to instantiate information hiding multiple instances of the ADT fall onto ADTs, too G Ada packages, Modula modules, etc.

University of Washington • CSE583 • D. Notkin © 2000 13 University of Washington • CSE583 • D. Notkin © 2000 14

Classes The classic example: a stack

G To the first order, an ADT is called a class class Stack[T] { s:Stack[int] := in an OO language push(item:T):void new Stack[int]; – Data structures are called objects and pop():T s.push(3); instances top():T s.push(5); – Operations are called methods size():int print(s.pop()); – Data inside the class are called instance } variables Polymorphic Message send: G (Later, some discussion of class vs. type) “Ask the object to do something” Method Instantiation

University of Washington • CSE583 • D. Notkin © 2000 15 University of Washington • CSE583 • D. Notkin © 2000 16

Two implementations Inheritance Instance variable class Stack[T] { class Stack[T] { G private: private: Define new class as an incremental items:array[10] of T; items:list[T] := nil; modification of an existing class public: public: push(item:T):void { push(item:T):void { G Perhaps the most recognizable items[top] := item; items.add_first(item); aspect of OO languages and top := top + 1; pop():T { pop():T { return programs top := top - 1; items.remove_first(); – ADTs but no inheritance does not return items[top]; size():int {return size():int {return top;} items.length(); usually earn the OO moniker } Method implementation

University of Washington • CSE583 • D. Notkin © 2000 17 University of Washington • CSE583 • D. Notkin © 2000 18

3 class ColorRectangle Inheritance Example inherits Rectange { private: color:Color; G New class is subclass of the original superclass class Rectangle { private: public: G By default, subclass inherits the superclass’ center:Point; draw(screen:ODev):void methods and instance variables h,w:int; {…} } G Can add more methods and instance variables public: area():int in the subclass r:Rectangle := new {return h*w;} Rectangle; G Can override (replace) methods in the subclass draw(screen:ODev):void cr:ColorRectangle := new {…} – But usually cannot override instance variables ColorRectangle; move(newc:Point):void print.r.area(); {…} print.cr.area(); … r.draw(); } cr.draw();

University of Washington • CSE583 • D. Notkin © 2000 19 University of Washington • CSE583 • D. Notkin © 2000 20

Benefits of inheritance Classic hierarchies

G Achieve more code sharing by factoring G A square is-a rectangle is-a polygon is-a code into common superclass 2D-shape – Encourages development of rich libraries of G related data structures A domestic cat (species) is-a lesser cat – Increases reuse (genus) is-a cat (family) is-a meat-eater (order) is-a (class) G May model real world scenarios well mammal – Use class to model different things – mammalia.carnivora.felidae.felis.cattus – Use inheritance for classification of things – Herding cats is not for wusses • Subclass is a special case of superclass

University of Washington • CSE583 • D. Notkin © 2000 21 University of Washington • CSE583 • D. Notkin © 2000 22

The world is not perfectly Rich OO hierarchies G class java.awt.Component (implements hierarchical java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable) G Smalltalk-80, Java JDK, … G • class java.awt.Button An elephant is a mammal •Magnitude • class java.awt.Canvas G •Association An elephant is a gray thing • class java.awt.Checkbox (implements • java.awt.ItemSelectable) – Unless it is albino •Date • class java.awt.Choice (implements java.awt.ItemSelectable) G •Number An elephant is a big thing • class java.awt.Container •Float G • An elephant has four legs •Fraction class java.awt.Panel • • class java.applet.Applet – Unless it lost one • •LargeNegativeInteger class java.awt.ScrollPane G …leads to issues in multiple •LargePositiveInteger • class java.awt.Window •SmallInteger • class java.awt.Dialog inheritance… • •Time class java.awt.FileDialog

University of Washington • CSE583 • D. Notkin © 2000 23 University of Washington • CSE583 • D. Notkin © 2000 24

4 Pitfalls of inheritance Dynamic binding

G Often overused, especially by novices G Allow subclass to be r:Rectangle := … cr:ColorRectangle := … G Code gets fragmented into small, factored used wherever a superclass is expected r := cr; pieces … – Allows reuse of G r.draw(); Tracing control logic of code is harder superclass’ code G Simple extension and overriding may be G When message is sent, which draw is invoked? too limited proper operation is – Ex: exceptions in classification hierarchies located and invoked

University of Washington • CSE583 • D. Notkin © 2000 25 University of Washington • CSE583 • D. Notkin © 2000 26

Dynamic binding (more) Method lookup

G This is a new kind of polymorphism: G Given a message obj.msg(args) subtype (inclusion) polymorphism G Start with run-time class C of obj (the – We’ll come back to this later “receiver”) G Dynamic binding requires run-time class G If msg is defined in C, invoke it information for each object G Otherwise, recursively search in the – Needed to figure out proper method to invoke superclass of C G Also known as message passing, virtual G If a match is never found, report run-time function calling, error (“Do not understand”) application – In a statically typed OO language, this error will never be reported

University of Washington • CSE583 • D. Notkin © 2000 27 University of Washington • CSE583 • D. Notkin © 2000 28

Example: displaying shapes in list Benefits of dynamic binding

forall s:Shape in scene do forall s:Shape in scene do G if s.is_rectangle() then s.draw(); Allows subtype polymorphism and rectangle(s).draw(); end elseif s.is_square() then class-specific methods square(s).draw(); G elseif… Allows new subclasses to be added else without modifying clients error(“unknown Add new shapes? shape”); G fi More important than inheritance? end

University of Washington • CSE583 • D. Notkin © 2000 29 University of Washington • CSE583 • D. Notkin © 2000 30

5 Pitfalls of dynamic binding Time for questions and comments

G Makes logic of program harder to G Specific follow questions about OO: why, what, G Adds run-time overhead how? – Space for run-time class information G Observations from experience – Time to do method lookup about what • But only an indirect jump, not a search aspects of OO are most crucial

University of Washington • CSE583 • D. Notkin © 2000 31 University of Washington • CSE583 • D. Notkin © 2000 32

Name vs. structural equivalence Types

G Under what conditions are instances record cartesian {x,y: float}; of two types the same? record polar (r,theta: float}; a,b: cartesian; – Constrains assignment (and related c: polar; operations) in most languages … G Arises even in “old” imperative a := b; languages like Pascal c := b; a.x := c.theta;

University of Washington • CSE583 • D. Notkin © 2000 33 University of Washington • CSE583 • D. Notkin © 2000 34

Polymorphism Strachey (1967)

G A walk through some definitions G "Parametric [true] polymorphism is obtained when a function works G Many from the OO FAQ on the web uniformly on a range of types; these G It’s more than just definitions types normally exhibit some common structure – At the same time, many of the G “Ad-hoc polymorphism is obtained when definitions are definitely tricky (or a function works, or appears to work, on worse) several different types (which may not exhibit a common structure) and may behave in unrelated ways for each type”

University of Washington • CSE583 • D. Notkin © 2000 35 University of Washington • CSE583 • D. Notkin © 2000 36

6 Cardelli and Wegner (1985) Definitions

G Expand on Strachey’s definition by G Polymorphic Languages: adding “inclusion (or subtype) – Some values and variables may have more polymorphism” than one type Polymorphism G Polymorphic Functions: – Functions whose operands (actual parameters) can have more than one type Universal ad hoc Universal ad hoc G Polymorphic Types: – types whose operations are applicable to operands of more than one type Parametric InclusionInclusion Overloading Coercion

University of Washington • CSE583 • D. Notkin © 2000 37 University of Washington • CSE583 • D. Notkin © 2000 38

More definitions Universal polymorphism

G Parametric Polymorphism: G Parametric and inclusion are closely related – A polymorphic function has an implicit or explicit type – Implementation approaches are distinct, however parameter that determines the type of the argument for each application of that function G Parametric polymorphism is referred to as • Ex: A list of ints is not a list of strings, but they are both generics lists – Each generic instantiation can create a specialized G Inclusion Polymorphism: version of the code – An object can be viewed as belonging to many • Ex: STL (standard library) different classes that need not be disjoint; that is, G there may be inclusion of classes In a "true polymorphic system", only a single • Ex: a ColorRectangle is also a Rectangle implementation is used

University of Washington • CSE583 • D. Notkin © 2000 39 University of Washington • CSE583 • D. Notkin © 2000 40

How do we determine if a type A is Inheritance (Cardelli/Wegner) a subtype of a type B? G on record types G A <= B means A is a subtype of B corresponds to the concept of G Consider types as records inheritance (subclass) in languages, – A must have all the fields that B has; A especially if records are allowed to can have more fields have functional components G For all fields in common, – [These functional components in fA <= fB records are methods]

University of Washington • CSE583 • D. Notkin © 2000 41 University of Washington • CSE583 • D. Notkin © 2000 42

7 Example OO languages have methods, too

type object = (age : int) type 2V-garage = G How does subtyping play here type vehicle = (v1 : vehicle, G (age : int, v2 : vehicle) Again, the question is, under what speed : int) type 2C-garage = conditions is it meaningful to apply a type machine = (v1 : car, function to an argument? (age : int, v2 : car, G The basic rule is: fuel : string) j : junk) type car = type 2M-garage = – Given (age : int, (v1 : machine, • f: S → T speed : int, v2 : machine) • a : S’ and S’ <= S fuel: string) – Then • f(a) is meaningful and f(a): T

University of Washington • CSE583 • D. Notkin © 2000 43 University of Washington • CSE583 • D. Notkin © 2000 44

Example Further example

G Consider any function g: t → car G Now consider – Ex: serial_number: int → car – speed: vehicle → int G Since g returns a car, it necessarily also G We can use this to determine the speed of returns a vehicle, since a car (because it is-a vehicle) car <= vehicle G This means that G That means that – (vehicle → int) <= (car → int) because (t → car) <= (t → vehicle) car <= vehicle – because car <= vehicle G Or, more generally – (vehicle → t) <= (car → t) because car <= vehicle

University of Washington • CSE583 • D. Notkin © 2000 45 University of Washington • CSE583 • D. Notkin © 2000 46

Note carefully Contravariant typing

G The reversal of the two examples, depending on G This of rules leads to the notion of whether the subtype relation is on the left or the contravariant typing righthand side of the function arrow G Again, it ensures that if you have A <= B G Cardelli argues this leads to the basic rule for a:A b:B subtyping of functions: and and then you can always a b – if S’ <= S and T <= T’ safely use where you had , and then S → T <= S’ → T’ G you’ll never have a reference to an – Because you can generally constrain the domain of a instance variable that is unknown or to a function and unconstrain the range of a function, function that is not meaningful without harming the function

University of Washington • CSE583 • D. Notkin © 2000 47 University of Washington • CSE583 • D. Notkin © 2000 48

8 Example Contravariant?

2Dpoint = G For this example, in Bool> 2Dpoint <= 3Dpoint, 3Dpoint = 3Dpoint <= 2Dpoint, Bool>

University of Washington • CSE583 • D. Notkin © 2000 49 University of Washington • CSE583 • D. Notkin © 2000 50

Covariance Some issues in OOP

G The covariant rule is different, swapping G Basic object model the function relationships – Hybrid vs. pure OO languages – if S’ <= S and T <= T’ – Class-based vs. classless (prototype-based) then S’ → T’ <= S → T languages G This allows different programs to be – Single vs. multiple dispatching written, but it cannot guarantee that a “do – Single vs. multiple inheritance not understand” error will never arise G Type checking – Eiffel uses covariance checking – Types vs. classes – It uses “system validity checking” to catch – Subtype polymorphism some type errors

University of Washington • CSE583 • D. Notkin © 2000 51 University of Washington • CSE583 • D. Notkin © 2000 52

Hybrid vs. pure object model Why hybrid?

G In a pure object model, everything is an G Primarily because of performance object – Who wants to ask an integer to dispatch a – Not only user-defined objects, but , method to add an integer to it? , floats, lists, etc. – Even “just” an added indirection can be • 3.+(4) costly, if done frequently enough G Everything is instantiated, everything is G So, hybrid languages (C++, …) allow the dynamically dispatched, etc. programmer to choose what is an what isn’t an object G This gives a terrifically consistent – Usually with some constraints; for example, programming model constraining non-objects to a predefined set G Ex: Smalltalk-80, Cecil, … of types

University of Washington • CSE583 • D. Notkin © 2000 53 University of Washington • CSE583 • D. Notkin © 2000 54

9 Class-based vs. classless How does it work? Delegation languages G Most OO languages have classes G Given a message obj.msg(args) G Some are instead classless G If msg is defined in obj, invoke it – Also, prototype-based G If not, the msg is passed on to another G Why? object that obj “delegates” to G The distinction between classes and – In some languages, there may be more than objects is important but tricky one delegate – Classless languages eliminate the distinction G If no delegate exists, then it’s an error – In principle, this gives a clearer programming model, just like a pure object model does

University of Washington • CSE583 • D. Notkin © 2000 55 University of Washington • CSE583 • D. Notkin © 2000 56

How does it work? How to create objects?

G Usually, a programmer simulates a G In class-based languages, a class holds a class hierarchy constructor (new method) that creates new instances of that class G A “regular” object delegates to a – This isn’t always exactly right, but it’s close “class” object G In classless languages, there is an object G A “class” object delegates to its called a prototype that knows how to “superclass” object clone itself to create new objects

University of Washington • CSE583 • D. Notkin © 2000 57 University of Washington • CSE583 • D. Notkin © 2000 58

The Smalltalk-80

G Smalltalk-80 is a class-based language G If classes are objects, what is their class? G And it has a pure object model G For each class in the system, there is an associated G That is, everything is an object, and – Each metaclass is constrained to have a everything has a class single instance: the given class object G This means that a class is actually an – The Smalltalk system creates the associated object, since everything is an object metaclass when you create a class G If you don’t like how classes work in Smalltalk, you can change the…metaclass class

University of Washington • CSE583 • D. Notkin © 2000 59 University of Washington • CSE583 • D. Notkin © 2000 60

10 Single vs. multiple dispatching But…

G Resolving obj.msg(args)is G This “single G Two different code generally done on the class of obj dispatching” can lead bodies to contorted code – + for int, + for float alone G How to handle? G – The class of args, for instance, is – 3+1 Two cases inside immaterial – 4.1+5.9 each code body – 2+6.5 – One that coerces – (This is true even in classless – 3.5+8 the argument, one languages) that doesn’t

University of Washington • CSE583 • D. Notkin © 2000 61 University of Washington • CSE583 • D. Notkin © 2000 62

Multiple dispatch Static type checking

G Allows the classes of more than just G Types can be separated from the receiver to determine which classes method body is invoked – Types can define signatures – Classes can define implementations G interface vs. class in Java

University of Washington • CSE583 • D. Notkin © 2000 63 University of Washington • CSE583 • D. Notkin © 2000 64

Next week

G We’ll look in more detail at some languages that make many of these points more concrete

University of Washington • CSE583 • D. Notkin © 2000 65

11