Quick viewing(Text Mode)

Lecture 22: OO Languages: Smalltalk & C++ Smalltalk Class Commands

Lecture 22: OO Languages: Smalltalk & C++ Smalltalk Class Commands

class

class name Point super class Object Lecture 22: OO Languages: class var instance var x y Smalltalk & ++ class messages and methods !...names and code for methods..." CSC 131 instance messages and methods moveDx: dx Dy: dy || Spring, 2019 x <- dx+x y <- dy + y x Kim Bruce ^ x ...

Commands Run-time representations

Point class x • Loops example: superclass y 1 to:10 do:[:i| Point object Transcript show: (i asString). ]. methods • Conditional class - (x>0) ifTrue:[ x:=x+1. ] ifFalse:[ x:=0 ]. Method dictionary - true and false are special values like x 2 code encodings newX:Y: ... code y 3 move code Dynamic Method Invocation Key ideas of Smalltalk

• Everything is an object • Start with object’s class and search up superclasses. • Information hiding - instance variables protected. • When call method inside, start search from self again. • Dynamic typing, so determined by whether can masquerade -- “message not • Most other OO languages do not implement dmi in understood” this way -- too inefficient! • Inheritance distinct from subtyping removeFirst, removeLast, removeFirst:, and removeLast: defined for Intervals. 6 Interfaces Versus Inheritance removeFirst, removeLast, removeAtIndex: Figure 5 shows the Smalltalk inheritance hierar- and removeAllSuchThat: defined for LinkedList chy (in bold) superimposed on the protocol hierarchy after: and before: moved to SequenceableCol- of Figure 4 (dotted lines). This is a concrete illustra- lection tion of the difference, even at a syntactic level, be- addFirst:, addLast:, add:before:, add:after:, tween inheritance and conformance [CHC90, Syn- addAllFirst:, addAllLast:, and add:beforeIndex: der86]. There are two cases where the hierarchy and canceled from SortedCollection. protocol hierarchies are in direct conflict: Dictionary and SortedCollection. Dictionary inherits from 5.2 Extending the Analysis but its protocol does not conform to Set’s. This is The process for analyzing class libraries can be because DictionarySmalltalk cancels several of Set’s methods. applied to other parts of the Smalltalk. One area that SortedCollection has a similar pattern of inheritance would benefit from examination is the classes. without conformance. These classes are conceptually similar to collections, Collection but are implemented in an entirely different part of the class system. Indexed A Stream is a destination or source of values. Collection Streams are part of the collection classes but are not well integrated with the other collections. This sec- Set Updatable tion discusses how they could be unified with other Collection collections ReadStream Mapped Dictionary Sequenceable Extensible C++ Collection Collection Representation : V* Collection Bag isEmpty ρ = ( #R = 0 ) Poppable Collection #R > 0 next R' = ρ•R Array Interval Internally #R > 0 peek ρ = R[1] Removable The next method has the same specification as Collection the removeFirst method in OrderedCollection. The String fact that it removes the first element instead of the last Ordered Sorted is merely an artifact of the specification; it is not vis- Collection Collection & ible to the client. Similarly, peek corresponds to the LinkedList first method. Figure 5: Interfaces versus Inheritance WriteStream Representation R : V* Another significant deviation centers around Se- quenceableCollection, which has inheritors nextPut: x R = R'•x (subclasses) with various combinations of protocols contents ρ = R unrelated to SequenceableCollection. Some of the subclasses (Array and String) are Updatable but not The method nextPut: has the same specification Extensible, since they support at:put:. Other sub- as addLast: in OrderedCollection, but is indepen- classes (LinkedList and SortedCollection) are Ex- dent of the actual ordering used. Renaming the next- tensible but not Updatable, since they support add:. Put: to be add: allows for more polymorphism; A final one (OrderedCollection) is both Extensible WriteStream then conforms to ExtensibleCollec- and Updatable. The abstract classes in Smalltalk tion. act as for methods that depend upon a key subclass responsibility method; to express this struc- C++ Design Goals Additions to C

• Data abstraction & OO features • type bool • Better static type checking • reference types & call by reference • Backwards compatibility w/ C • user-defined overloading • Efficiency: If you do not use a feature, you • templates should not pay for it • exceptions • Explicitly hybrid language -- C w/abstraction • public or private inheritance

Problems Casts & Conversions

• Implicit conversions: • Confusing casts and conversions - from short to int • Objects allocated on stack - class { public: B (A a) {} }; A a; B b = a; - what happens w/subtyping? truncation! • Explicit conversions: - C c; * d; d = (D*) &c; d -> DonlyMeth(); • Overloading methods -- see earlier examples! • Try to avoid problems by using new casts: - static_cast, dynamic_cast, reinterp_cast, const_cast • (later) - dynamic_cast checks using run-time type info (RTTI) - reinterp_cast trusts Objects on stack OO Features in C++ • Visibility • Doesn’t interact well with subtyping. - Public, protected, private - Friends ... • Point p; // allocates point on stack • Virtual vs. nonvirtual functions • ColorPoint cp(3,4,blue); - don’t pay the price of dynamic method invocation • p = cp; // slices and converts to Point • Implemented via vtable • Call by value has similar problems - no search necessary • What about reference parameters to methods? - static typing makes efficient rep possible - efficient iff subtype fom inheritance!

VTable for Virtual methods C++ vs Smalltalk implementation Point object Point vtable vptr getX code x 2 ... code translate code • No search in C++ since offset for given method y 3 same in base and derived classes ColorPoint object • Smalltalk has no type declaration ColorPoint vtable vptr - value not known to be subtype of declared type getX no idea where method is located x 2 ... - y 3 translate color red getColor code Abstract classes Multiple Inheritance

• Have at least one method undefined • Appealing: TA derived from Student and Teacher. • “Pure” leaves all undefined • Added to C++ and Smalltalk. In Eiffel from • Can’t construct, but can inherit from beginning. • Derived subclasses can be used as subtypes of • Problems conceptually and with abstract base class. implementation

MI in C++ Representing MI

class S {...} TA as S vtable class T{...} ps,pta TA object class TA: public S, public T code vptr {...} code S data pt ... TA as T vtable vptr TA* pta = new TA(); code S * ps = pta; T data ... code T * pt = pta; TA data code What if T and TA both define virtual f? T methods expect inst vbles starting at pt How get access to instance vbles fom S? Conceptual Problems w/ MI Solution

A • Most multiple inheritance in C++ involves pure base classes. B C • Java: Single inheritance, but can implement multiple interfaces. D • Avoids problems. Diamond Inheritance: Suppose A has virtual f • Traits (e.g., in Scala) are modern alternative. and B and C override it. Which version is inherited in D?

C++ Summary C++ Humor

C++: Hard to learn and built to stay that way. • One of most complicated languages ever • Java is, in many ways, C++--. - design by accretion • • How C++ is like teenage sex: • Meets design goals but very hard to get right 1. It is on everyone's mind all the time. Everyone talks about it all the time. “C makes it easy to shoot yourself in the foot. In C++ 2. - Everyone thinks everyone else is doing it. it's harder to shoot yourself in the foot, but when you 3. do, you blow off your whole leg.” -- Stroustrup 4.Almost no one is really doing it. 5. The few who are doing it are: • Memory management is big problem A. Doing it poorly. • Most learn a subset. B. Sure it will be better next time. C. Not practicing it safely. Java Design Goals

• Portability across platforms • Reliability Java • Safety (no viruses!) • Dynamic Linking • Multithreaded execution • Simplicity and Familiarity • Efficiency

Java Exceptions & Subtyping • Original implementations slow - Compiled to JVML and then interpreted - Now JIT • All non-Runtime exceptions must be caught or - Garbage collection declared in “throws” clauses Safety - 3 levels: • - void method readFiles() throws IOException {...} - Strongly typed Suppose m throws NewException. - JVML also checked before execution • - Run-time checks for array bounds, etc. • What are restrictions on throwing exceptions if m overridden in subclass? Masquerade! • Other safety features: - No pointer arithmetic, unchecked type casts, etc. - Super constructor called at beginning of constructor Simplify from C++ Interfaces

• Purely OO language (except for primitives) • All objects accessed through pointers • Originally introduced to replace multiple inheritance - reference • No multiple inheritance -- trade for interfaces • Allows pure use of subtype polymorphism w/ out confusing with implementation reuse. • No • Slower access to methods as method order not • No manual memory management guaranteed • No automatic or unchecked conversions

Encapsulation Problems w/Packages • Generally tied to directory structure. • Classes & interfaces can belong to packages: package MyPackage; • Anyone can add to package and get privileged access public class C ... • If no explicit package then in “default” package • All classes/interfaces w/out named package in default package (so all have access to each • public, protected, private, “package” visibility other!) • Class-based privacy (not object-based): • No explicit interface for package - If method has parameter of same type then get access Abstraction barriers not possible for interfaces. to privates of parameter • Discourages use of interfaces for classes.