<<

Interfaces for Strongly-Typed Object-Oriented Programming

Peter S. Canning, William R. Cook, Walter L. Hill, Walter G. Olthoff

Hewlett-Packard Laboratories P.O.Box 10490, Palo Alto, CA 94303-0971

Abstract of untyped object-oriented languages like Smalltalk. In- terpreting interfaces as types in a polymorphic lambda This paper develops a system of explicit interfaces calculus is our main technique for moving towards that for object-oriented programming. The system provides goal, We have implemented a type-checker for a typed the benefits of module interfaces found in languages programming language and are using it to test the feasi- like Ada and Modula-2 while preserving the expressive- bility and value of interfaces for object-oriented pro- ness that gives untyped object-oriented languages like gramming. Smalltalk their flexibility. Interfaces are interpreted as polymorphic types to make the system sufficiently pow- Explicit interfaces are useful for clarifying the erful. We use interfaces to analyze the properties of in- role of inheritance in object-oriented programming lan- heritance, and identify three distinct kinds of inheritance guages. Using recent work on the semantics of inherit- in object-oriented programming, corresponding to ob- ance, we describe three distinct kinds of inheritance in jects, classes, and interfaces, respectively. Object inter- object-oriented programming, corresponding respective- faces clarify the distinction between interface contain- ly, to objects, classes, and interfaces. Interface inherit- ment and inheritance and give insight into limitations ance is important in reinforcing the difference between caused by equating the notions of type and class in many interface compatibility and inheritance. typed object-oriented programming languages. Interfac- es also have practical consequences for design, specifica- It also gives insight into the limitations of typed ob- tion, and maintenance of object-oriented systems. ject-oriented languages that equate the notions of type and class. 1. Introduction In a more practical vein, this work addresses im- portant needs and opportunities in object-oriented soft- An important contribution of languages like Ada, ware development. At Hewlett-Packard, large-scale ob- Mesa, and Modula-2 is the explicit separation of the in- ject-oriented development has suggested the terface and implementation of program modules. The in- need for the benefits that interfaces provide. Object in- terface provides a boundary between the implementa- terfaces provide a useful framework for specifying ob- tions of an abstraction and its clients. It limits the jects when designing a system. Checking them should amount of implementation detail visible to clients. It yield significant gains in productivity and quality in ob- also specifies the functionality that ject-oriented software development. Interfaces may also must provide. be the basis of new tools for organizing object-oriented systems. In this paper we develop a system of explicit in- terfaces for object-oriented programming. The primary In Section 2, we review the significance of inter- goal for the system of object interfaces presented here is faces in large-scale software development. Section 3 de- to allow interface compatibility to be checked at com- velops the notion of object interface in contrast with pile-time (eliminating the possibility of certain run- object implementation and shows the essential role time errors) while preserving the power and flexibility played by polymorphic types. Section 4 discusses vari- Permission to copy without fee all or part of this material is granted provided ous forms of inheritance in object-oriented program- that the copies are not made or distributed for direct commercial advantage, ming, and the difference between the interface and im- the ACM copyright notice and the title of the publication and its date appear, plementation hierarchies in typed object-oriented pro- and notice is given that copying is by permission of the Association for Computing Machinery. To copy otherwise, or to republish, requires a fee gramming. Section 5 briefly compares this work with and/or specific permission. other approachesto typed object-oriented programming. 0 1989 ACM 089791-333-7/89/0010/0457 $1.50

October 1-6, 1989 OOPSLA ‘89 Proceedings 457 2, Interfaces ent, they admit an analogous type-theoretic interpreta- tion. In all these cases, interface checking reduces to “The most important recent development in type-checking, for which there is an existing technolo- programming languages is the introduction of gy. Interfaces consisting only of operation names and an explicit notion of interface to stand be- types are weaker than complete behavioral specifica- tween the implementation of an abstraction and its clients.” tions. Nevertheless, this compromise has proven success- ful in practice, both in terms of expressiveness, user ac- Burstall and Lampson, 1984 ceptance and automated support from compilers and pro- When analyzing and designing software systems, gramming environments. interfaces enforce conceptual discipline and provide mod- ular specifications and documentation. Checking interfac- 30, Objects and Their Interfaces es may detect conceptual as well as superficial errors. Interfaces are also used in code to declare or annotate variable or operation names, making programs easier to understand and maintain. They provide for generic mod- 3.1. Introduction ules and allow categorizing implementations, support- In this section we develop the notion of separat- ing reuse and administration. In all these forms, ing interface from implementation in object-oriented interfaces include the idea of a contractual agreement be- programming. Our language model for object-oriented tween providers and users of system components, and programming is patterned after Smalltalk- [GR83]. what it means for the terms of the agreement to be sat- Object-oriented systems are characterized by objects isfied. On the other hand, the contract is given in an ab- which group together data and the operations for manip- stract form that deliberately disregards details of how ulating that data. The operations, called method& can be to accomplish its provisions. invoked only by sending messages to the object. Sending Ideally, interfaces should contain a formal de- a message names the operation and supplies necessary ar- scription of the behavior of operations, for example as a guments, but does not determine how the operation is logical theory. Module connections would then be vali- implemented, The target of the message (the receiver) dated by theorem proving. There is much work in pro- determines what action takes place when the message is gram specification and validation that is motivated by received. Since the data (instance variables) in an object this model lEM85, GHW85]. However, this approach can be accessed only by the methods of that object, and requires mechanical theorem proving support which is methods can be invoked only by sending messages, ob- currently an obstacle for including it in practical pro- jects are encapsulated data abstractions. gramming languages. Moreover, the application of speci- Our goal is to provide a language with the flexi- fication and validation techniques to object-oriented pro- bility of Smalltalk, but with the additional structure gramming is not yet well understood. and protection that comes from making interfaces ex- Interfaces have been used in a variety of ways in plicit, and verifying the safety of message sends at com- traditional software development. During design, inter- pile-time. The rest of this section describes object im- faces are typically semi-formal descriptions of how an plementations and then object interfaces. The basic ideas abstraction interacts with the rest of a system. Together in this section have appeared in previous work, as dis- with appropriate naming and documentation conven- cussed in Section 5. In our treatment of recursive and tions, they provide partial specifications. In the imple- polymorphic interfaces, we have attempted greater con- mentation phase, interfaces usually describe the names sistency with object-oriented programming. and the parameter and result types of operations sup- plied by a module as in Ada, Mesa, and Modula-2. In Ada, for example, one distinguishes between package 3.2. Object Implementations specification and package body. The package specification As described above, an object is a collection of in- presents an interface as a list of type, procedure and otb- stance variables and methods. Each method provides a er declarations. Explicit interfaces are important in real- concrete implementation of some abstract operation. A izing data abstraction, data encapsulation and separate compilation. method can implement an operation by manipulating the instance variables, giving them new values or sending In Ada, Mesa, and Modula-2, the module inter- messagesto them, or by sending messagesto self. Fig- faces can be interpreted as types [BL84]. While the ob- ure 1 shows an example of a definition of an object ject interfaces discussed below are structurally differ-

October l-6, 1989 458 OOPSLA ‘89 Proceedings instance will have, the code for each method, and how object origin implements Point to create instances. Figure 3 shows a class for objects variable rho:Real := 0.0 similar to the object from Figure 1. variable theta:Real := 0.0 class polargoint(x:Real, y:Real) method x0 returns Real implements Point return rho * sine(theta) variable rho:Real := sqrt( (x*x)+(y*y)) method y() returns Real variable theta:Real := return rho * cosine(theta) arctangent(y/x)

method equal(p:Point) method x0 returns Real returns Boolean return rho * sinettheta) return (self.x() = p.xO) and (self.yO =~p.yO) xnethod y() returns Real . . . return rho * cosine(theta)

Figure 1 method move(dx:Real, dy:Real) returns Point which uses polar coordinates to represent a point in the return plane. new myclass(self.xO+dx, This example illustrates a common characteristic self.y()tdy) of object implementations, namely their recursive struc- ture. The recursive references are indicated by occurrenc- method equal(p:Point) es of self in a method. The recursion is not obvious in returns Boolean the textual form because se1 f is a pseudo-variable that return (self.xO = p.xO) and is implicitly declared. The graphical representation of (self-y0 = p.yO) Figure 2 should make the recursion apparent. Figure 3 When the equal method is invoked, the pseudo- variable self is bound to the receiver of the message Instances of class polar_point will share the (i.e. the object origin). In this way, when the equal same structure and methods, but can have different val- method sends the x message to self, the appropriate x ues for their instance variables. The objects that are cre- method is invoked. ated from polar_point have the same recursive struc- In our system as in Smalltalk, an object may be ture that the object origin did. Figure 3 illustrates an- an instance of a class. A class is a pattern that can be other form of recursion that occurs in classes. This used to create many objects with common structure. Spe- recursion is indicated by occurrences of the pseudo-vari- cifically, a class describes what instance variables each able myclas s which is used to create an object of the sameclass as self (myclass has the same meaning as the expression self class in Smalltalk). As with riqin obiect object recursion, the graphical presentation of Figure 4 +--id- equa 1 method should clarify this structure. In this example, the recur- sive reference is to class polargo int .

3.3. Object Interfaces As described earlier, an interface provides the in- formation necessary to use a module. In object-oriented systems, the only way to use an object is to send mes- sages to it, so the interface to an object is a description of the messages the object understands. These collec- tions of messages are known as protocols [GR83]. In Figure 2 our system we define an object interface to be such a col-

October l-6, 1989 OOPSLA ‘89 Proceedings 459 W any object that can handle a given of Instance polargoint class messages (sati@es an interface) in a con- text that sends just those messages / (re@es that interface) independent of how the messages are implemented inside the object. This provides a form of poly- morphism that allows multiple implemen- tations of an interface to interact within the same program (in contrast with other move method programming paradigms). For example, a function that requires a parameter satisfy- ing the point interface and computes its self distance from the origin, works equally well on objects that internally use polar coordinates and on objects that use rectan- Figure 4 lection, where each message is given with the interfaces gutar coorctmates as long as both objects understand all for the parameters it requires and for the result it re- the messagesin the point interface. turns. As an example, the interface for the planar point objects described above is shown in Figure 5. interface Point x0 returns Real Like object implementations, object interfaces y 0 returns Real have some interesting structural aspects which are illus- move(Rea1, Real) returns Point trated by this example. equal(Point) returns Boolean 1. Interfaces are constructed from other in- terfaces. The Point interface makes use Figure 5 of the Real and Boolean interfaces. L The Boolean interface would contain messageslike not, and, and or. On closer examination, we see that this function 2. Interfaces are often recursively defined. will also work with objects thar understand other mes- There are two places this recursion ap- sages in addition to those in the point interface. In its pears, in a parameter interface of a mes- most general form, this idea, called inte&ce contuin- sage (e.g. equal), and in the result mentl, provides flexibility in the use of code (and ob- interface of a message(e.g. move). jtxts). hfOrmally, we say Big contains Small if an 3. Interfaces do not contain information object satisfying interface Big can be used in a context about the internal representation of the ob- requiring interface Small. More precisely, Big con- ject. The x and y messages in the Point tains Small if it contains all the messages that Small interface provide information about an ob- does, and for each of these common messages, each pa- ject, but they do not imply that the object rameter interface for Small contains the corresponding contains x and y instance variables. parameter interface for Big while the result interface for Big contains the result interface for Small. The In other programming paradigms, interfaces are important thing to notice here is that the condition on used to ensure certain correctness properties of pro- parameter interfaces is reversed. grams. In object-oriented programming, the correctness property is that messages sends are safe. This means that While this reversal looks counter-intuitive, the a run-time message error will never occur. Safety is example in Figure 6 proves that the non-reversed condi- guaranteed by compile-time type-checking which uses tiOn (i.e. claiming Actual-Parameter contains For- the declarations of instance variables and formal parame- ma1 Parameter) is incorrect. The function test re- ters (e.g. p:Point in class polargoint) to ensure qU& an argument satisfying Formal-Parameter, that variables always refer to objects that understand since it sends the message msg to its formal parameter. all the messagesthat are sent to them. * The propfztiesof interfacecontainment, or subtypepotymor- A significant part of the flexibility of untyped phism, which allowswriting programsthat work on valuesthat have types that are arbitrary subtypesof a particular type, are well object-oriented programming is the potential of using known[Car84].

460 OOPSLA‘89 Proceedings October l-6, 1989 Calling test with an actual parameter ob j that satis- interface ColorPoint fies Actual-Parameter will do p .msg (s).This in- x() returns Real vokes the msg method from ob j which expects a param- y() returns Real eter satisfying Big, but passes it s which only satisfies color (I returns Color Small. This is clearly incorrect as the msg method move (Real, Real) returns ColorPoint could send s a message that it doesn’t understand (i.e. a equal(ColorPoint) returns Boolean message in Big but not in Small) resulting in a run- time error. Figure 7

interface Formal-Parameter 4 describes another relation between interfaces, which msg (Small) returns Boolean solves this problem.

interface Actual-Parameter 3.4. msg(Big) returns Boolean In addition to subtype polymorphism, there is an- other of polymorphism known as parametric poly- function test(p:Formal-Parameter) morphism [CWSS] which provides the ability to write variable s:Small = . . . programs admitting a form of type parameterization. if p.msg(s) then . . . Due in part to their lack (or limited form) of paramet- ric polymorphism, most strongly-typed object-oriented variable obj:Actual-Parameter=... programming languages have sacrificed flexibility when compared with untyped object-oriented languages test(obj) [E1HJ87, Str861.

Figure 6 class stack[T] implements StackIT] variable elts:List[Tl := Since many object interfaces are recursive, it is im- new ListIT] portant to understand what interface containment means for recursively defined interfaces. As is typical for re- method push (x : T) returns nothing cursive structures, induction is used to determine wheth- elts := elts.prepend(x) er two recursive interfaces are in a containment relation. A recursive interface Big contains another recursive in- method pop 0 returns T terface Small if assuming Big contains Small implies variable tmp:T := elts.head() that the corresponding message parameter and result in- elts := elts.tai.10 terfaces in Big and Small are in the required contain- return tmp ment relations. Unfortunately the reversal of the interface con- I method top 0 returns T tainment relation between message parameter interfaces I return elts .head() combined with the recursive structure of object interfac- es leads to a problem in using interface containment in method empty?0 returns Boolean object-oriented programming. Many pairs of object in- return elts.empty?() terfaces that appear intuitively to be in a containment re- Figure 8 lationship are not. The interface to colored planar points in Figure 7 provides a good illustmtion. The ColorPoint interface does not contain the One use of parametric polymorphism is for build- Point interface because the equal message in the ing generic (or parameter&) modules. A simple ob- ColorPoint interface requires a ColorPoint param- ject-oriented example is the stack class of Figure 8. eter and that contradicts the constraint that message pa- Clearly, nothing in class stack depends on what rameter interfaces be in a reverse containment relation. type of elements are stored in the stack. It is important Interface containment with structured interfaces to be able to provide one stack class that can be reused is sufficient to type-check many object-oriented pro- for elements satisfying different interfaces and to be grams, but is too restrictive for the recursive interfaces able to type-check the class. For example, the result of that are appropriate for many Smalltalk classes. Section sending top to a stack of windows must satisfy the

October l-6, 1989 OOPSLA ‘89 Proceedings 461 Window interface. The major idea introduced by para- metric polymorphism is that of an interface variable. class set [T] implements Set [T] In class stack, T is an interface variable representing where T contains the interface of the objects stored on the stack. The in- equal(T) returns Boolean troduction of T makes it possible to declare variables I .. . with interface T and define methods that take arguments xnethod member? (x:T) returns Boolean or return results with interface T, and still type-check variable y:T the class definition. . . . Just as it is possible to have parameter&d class- if x.equal(y) then return TRUE es, it is also possible to have parameterized interfaces. I Class stack claims that it implements the parameter- 1.. ized interface Stack [T] shown in Figure 9. Interface Figure 10 Stack uses the interface variable T to express the fact that it is independent of the interface of the elements Suppose we want to add a method called se- stored in the stack. lect-nearest to class polar-point that takes a set of objects satisfying the point interface, and re- interface Stack [T] turns the element of the set that is closest to the receiv- push (T) returns nothing er. An obvious way to add select-nearest to the pop (1 returns T point interface wouldbe: top0 returns T empty? 0 returns Boolean select-nearest (Set [Point] 1 returns Point Figure 9 This is not really what we want. If we send se- For the stack class, T represents an arbitrary in- lect-nearest to an object along with a set of ob- terface. Sometimes it is necessary to restrict the inter- jects satisfying the Colorpoint interface, the type- face variable to interfaces that contain certain messages. checker has been told that we get back an object satisfy- Combining the ideas of interface variables and interface ing only the point interface (i.e. we lose the informa- containment into a notion called bounded parametric tion that we selected an element from a set of Color- polymorphism [CW85, CCH891 accomplishes this re- Po in t objects). The solution is to use bounded paramet- striction. Again this can be most easily explained using liC polymorphism again, this time on the an example (Figure 10). select - nearest method rather than on a class: The key point is that the member? method sends the equal message to a variable with interface T, so it select-nearestIT contains Point] would not type-check without restricting T to the inter- (s:Set [Tl) returns T faces that contain an equal message. This restriction al- This form of bounded parametric polymorphism re- so prevents the creation of sets of elements that do not stricts T to interfaces COntaining the Point interface. have an equal operation. It also ensures that the type-checker will know that The forms of parametric polymorphism shown so select-nearest returns a object that satisfies the far are not specific to object-oriented programming. appropriate interface. Bounded polymorphism as present- Similar functionality is available, for example, in ML ed here solves the problem for interfaces containing [H&IT881 and Ada DOD831. The following form for point. The full solution, which also handles interfaces methods however, is specific to and needed for object- like Colorpoint that are closely related but do not oriented programming. It requires a strict- contain point, requires a generalization of bounded ly more powerful than those of most languages2. polymorphism as described in [CCH89]. It is based on the idea of interface inheritance developed in Section 4.4. %lle first -order polymorphism found in ML [HMT88] will not handle this situation since the quantified type variable doe.s not occur at the outer- most level. The interfaces described here are interpreted in an extension of the higher-order system of Gird-Reynolds [Gir72, Rey74] , which is 3 The perceptive reader will recall that CoLorPoint does not con- sufficient,butmorecomplex[CHO88]. tain Point . For the moment assume that it does.

462 OOPSLA ‘89 Proceedings October1-6, 1989 recursion and inheritance and to apply it to strongly- object instrumented typed object-oriented programming. implements Point inherits origin 4.2. Object Inheritance variable x-count:Integer := 0 Object inheritance is the form of inheritance asso- variable y - count:Integer := 0 ciated with object recursion that was illustrated in Fig- method x () returns Real ure 2. It is used to create a new object from an existing x count := x count + 1 object (called a prc~otype) by describing how the new rSur:n origG.x() object differs from the prototype. These differences are expressed in terms of adding or replacing methods, and . . . adding instance variables. Methods that are not replaced are inherited from the prototype. Figure 11 demon- Figure 11 strates object inheritance by creating an instrumented planar point object (Figure l), that counts how many 4. Inheritance times the x and y messagesare sent to it. This object shows the change in recursive refer- ence that is characteristic of inheritance. When the 4.1. Introduction equal message is sent to instrumented, no equal method is found so the equal method defined by its This section discusses inheritance in object-orient- prototype (object origin) is invoked. However, when ed ‘languages and its relation to interfaces. The inherit- the equal method then sends the x message to self ance mechanism used here provides a unified framework (i.e. self.x()), the x method defined for instru- that describes the traditional forms of delegation and mented is invoked4. Thus the result of object inherit- class inheritance, and exposes new connections with in- ance is that the instrumented x method is invoked even terfaces. Interfaces have their own form of inheritance by message sends from methods originally defined for which is important for understanding the interfaces aris- object origin. Reinterpreting self in the context of ing from delegation [Lie861 and class inheritance instrumented accomplishes this result as illustrated [GR83], and explaining the difference between inhexit- graphically in Figure 12. ante and interface containment. An object’s interface includes all the messages As recent work has shown, inheritance is inti- from its prototype’s interface. In particular, an object mately connected to self-reference [Coo89a, CP89, can handle all the messages that its prototype sends to Red883. In these models, inheritance is defined as a self, Intuitively this suggests that an object’s inter- mechanism for deriving modified versions of recursive face contains the interface of its prototype. While this structures. The characteristic pattern of inheritance is is often true, it does not hold in general as discussed be- that self-reference in the inherited structure is changed to refer to the modified definitions. One result of this interpretation is that ev- ery recursive construct is an opportuni- instrumented object ty for inheritance. Recalling the three I 1 equal method forms of self-reference (object, class, - self and interface) presented in the last sec- x --+ equal. tion, this principle gives three corre- 1 sponding kinds of inheritance. The first X two of these correspond respectively to Y w notions of delegation and class inherit- ance. The notion of interface inheritance is new; it plays a crucial roIe in repre- Variables Variables senting the interfaces for objects ob- vx_count rho tained from the two other kinds of inher- 1 y-count 1 theta itance. The examples that follow serve I I I J to illustrate this relationship between Figure 12

October 1-6, 1989 OOPSLA ‘89 Proceedings 4.3. Class Inheritance Class inheritance is the form of inheritance associated with the recursion in class definitions described in Figure Instance rlargoint 4. It is essentially the form of inherit- r ance found in most object-oriented lan- Jonstructor guages. It is used to create a new class, class Zonstructor called the child class or subclass, from I an existing parent dass by describing Variables how the instances of the child class dif- Messages Messages move method fer from those of the parent class. As parent with object inheritance, class inherit- myclass ance provides for adding and redefining color methods, and adding instance variables equal self In addition, class inheritance takes into account recursion in the pseudo-variable H I myclas s. Figure 13 illustrates creat- L J J ing a class of colored points that inher- its from class polar-point (Figure Figure 14 3). Using class inheritance, new myclass is rein- class color_point( a :Real, terpreted as creating instances of class colorgoint. b:Real, However, since instantiating class colorgoint takes c:Color) an extra color argument in addition to the initialization implements ColorPoint arguments for class polar_point, the inheritance inherits polargoint(a,b) mechanism must provide a translation to create instanc- translating new myclass (x, y) es of class colorgoint using the initialization pa- to new myclass(x, rameters provided by class polar_point. This transla- Yl tion is provided in the inherits clause in Figure 13. self.color()) Using this translation, the class inheritance mechanism ensures that when a colored point is moved, it retains variable color:Color = c its color. Figure 14, shows the resulting system of classes and objects with the new connections for my- method color () returns Color class and self in the inherited move method. return color The translation mechanism described here, which is required for general class inheritance, goes beyond the method equal(p:ColorPoint) capabilities of current object-oriented languages [CCH, returns Boolean Coo89a]. While most object-oriented languages have a return (self.x() = p.x()) and notion of class inheritance, there are considerable differ- (self.yO = p.yO) and ences in the treatment of myc lass. In Eiffel [Mey87], (self.colorO =p.color()) creating values of type like Current corresponds to Figure 13 calling new myclass, while in Smalltalk, one in- vokes self class new. In some languages, including Class inheritance reinterprets self in the con- text of the new class just as object inheritance did. In 4 addition, it also reinterprets the pseudo-variable In this example, one might not have wanted calls to equal to incre- myclass. For example, class color_point inherits ment the counters. ‘Ihis effect could be provided by extending the usual the move method from polar-point, which contains: notion of inheritance to distinguish loose and tight references to self. Devising language mechanisms to express and apply such alter- return new myclass(self.xO + dx, natives is an interesting problem which we are currently investigating. self.yO + dy)

464 OOPSLA ‘89 Proceedings October 1-6, 1989 Ccc, there is no corresponding mechanisms; classes are Interface inheritance provides exactly the form of referred to only by explicit name. interface change that is required to express the effect of and class inheritance. Specifically, col- When comparing interfaces for the instances of object parent and child classes, the same considerations apply or_point is defined by inheriting polarJoint, and as were discussed for object inheritance above. Class in- the interface ColorPoint is produced by interface in- heritance from Point. Since ColorPoint does not heritance, however, introduces additional connections be contain Point, this shows that the class inheritance hi- tween the recursive structures of classes and interfaces. erarchy and the interface containment hierarchy are dis- Notice, for example, that the interface to the move method for a polar_point object is: tinct. The Eiffel language [Mey87] provides an implicit move(Real,Real) returns Point form of interface inheritance that occurs when the type whilefora color_point itis: like Current is used to type amethod. Ifthis meth- move (Real,Real) returns ColorPoint od is defined by a class P then like Current is bound to P for instances of class P. But if the method is Methods that return self in object or class in- inherited by a class C, then like Current represents heritance, or new myclass in class inheritance, im- C. However, the Eiffel type system in its current form pose recursion in the interfaces. As a result, the follow- is unsound [Coo891 because it assumes that instances of ing notion of interface inheritance plays a central role in sub-classes always satisfy the interfaces of their super- describing the interfaces of objects arising from object classes, which we have shown not to be the case in gen- and class inheritance. eral. A more detailed analysis of the properties of ob- 4.4. Interface Inheritance ject, class, and interface inheritance, and the relations be- tween them, is currently in preparation[CCXJ. Interface inheritance is the form of inheritance as- sociated with the recursive definition of object interfac- es described in Section 3.3. Interfaces are typically modi- 5. Related Work fied by adding new messagesor by changing the parame- ter or result interfaces of a message. Interface There have been several attempts to introduce in- inheritance allows this change to take place so that ev- terfaces into object-oriented programming. Efforts ery recursive reference is changed as well. As an exam- within the object-oriented language community include ple, the interface ColorPoint can be viewed as inherit- the work of Boming and Ingalls [BI82], the Emerald ing interface point, becausea messageis added and oc- group [BHJ87], and Johnson et al. [JGZ88], all of whom currences of Point are changed to ColorPoint. have a notion of interface as message protocol. [BI82] Abstractly, this mechanism is the same as the change of and 862881 describe type systems for Smalltalk with self in object or class inheritance. types based both on classes and protocols. The [BI82] work is less formal and does not distinguish interface Interface inheritance characterizes a collection of containment from inheritance; nevertheless, it captures interfaces that have similar recursive structure. All in- much of the essential structure of object interfaces. The terfaces that inherit from Point will have the form: more recent [JGZ88] work is interesting for its mixing of class-based and interface types, and has a limited interface X form of polymorphism as found in ML. Emerald intro- . . . duces interfaces to provide uniformity in a distributed move(Real,Real) return8 X object system. However, the interface system supports equal(X) returns Boolean only limited parametric polymorphism and there is no . . . notion of inheritance. Similarly, Modula-3 [CDK89] has This collection is different from the interfaces that are notions of object and interface, but without polymor- related by containment. For example, ColorPoint phism. does not contain Point, even though it is derivable by In most typed object-oriented languages, includ- inheritance. ing Simula, C++, and Eiffel, the notion of type is dif- ferent from ours. In those languages, classes are types, 5 ‘he effect can be simulated (although typing can stiJ.l be a pmbkm) by factoring all calls to the constructor through an ordinary message that so that a type gives information about how objects are must be manually redefined in each subclass. implemented. This improves performance and also pro- vides the benefits of static type-checking, but at a cost

October l-6, 1989 OOPSLA ‘89 Proceedings 465 in flexibility, which is significant for system develop- promising the programming model of untyped Small- ment. In addition to collapsing the distinction between talk. interface and implementation, the notions of interface Analogous to Ada’s package interfaces, explicit. containment and inheritance are confused[Coo89]. The re- object interfaces have many uses which bear on quality sult is that programs that would be correct in Small- and productivity in object-oriented software develop- talk cannot be type-checked in these languages. ment. These include compatibility checking, system de- From another direction, object-oriented program- sign and documentation, and software reuse. Interfaces ming has been studied in the typed functional program- are also the basis of the design of new tools for object- ming community [Car84, Car86, CW85, CM88, JM88, oriented software development. BL88, Wan891. While many features of our system were Interfaces help to clarify the role of inheritance derived empirically, its basic structure is generally con- in object-oriented programming, and to distinguish be- sistent with that earlier work. Our treatment of inherit- tween interface containment and implementation inherit- ance and polymorphism, however, gives a more faithful ance. There are different forms of inheritance corre- representation of conventional object-oriented program- sponding to objects, classes, and interfaces. In particu- ming than other type-theoretic work [CHOSS, CCH89, lar, delegation and class inheritance are given a unified CCHJ. Our treatment of is taken from treatment. Understanding their respective roles, along Cardelli [C&88]. The paper [BCG89] gives a semantics with the roles of interface containment and parametric for a language which shares most of the properties of polymorphism, leads to improved design of systems and our object interfaces. languages for object-oriented programming. The structure of object interfaces is different from interfaces in Mesa and Modula-2 modules or Ada packages. For example, with an Ada package providing 7. Acknowledgments complex numbers, the interface is used to check that the We would like to thank John Mitchell for help- package is used correctly, but it is not an interface to ing us with our type system and its semantics, and for individual complex numbers provided by the package. In bringing related work to our attention. We are grateful contrast, object interfaces are interfaces for individual to Alan Snyder for enabling and encouraging us to pur- data values (objects). This reflects a difference in the sue this work, and generously helping us along the way. way object-oriented programming distributes data and procedural information. Interfaces, and especially the notion of separate 8. Bibliography containment and inheritance hierarchies, suggest new [BCGS9] V. Breazu-Tannen, T. Coquand, C. Gunter, ways of organizing object-oriented systems. Tools for and A. Scedrov. “Inheritance and explicit co- managing such systems, such as the Smalltalk system ercion”. In Logic in Science, 1989. browser [GR831 which relies on the class hierarchy, can be extended. Not only are there new hierarchies avail- lJ=JW A. Black, N. Hutchinson, E. Jul, H. Levy, able, there are also important relations between them and L. Carter. “Distribution and abstract which can add power to these new tools. Interface check- types in Emerald”. IEEE Transactions on ing makes it possible to maintain relations dynamically Software Engineering, SE-13(l), 1987. between implementations and the interfaces that they [BI82] A. H. Boming and D. H. Ingalls. “A type satisfy. A software library can then organize classes us- declaration and inference system for Small- ing both interfaces and inheritance to classify them. The talk”. In ACM Symposium on Principles of development of interface-based tools is an active area of Programming Languages, 1982. applied research at Hewlett-Packard Laboratories. [BL84] R. Burstall, B. Lampson. “A kernel lan- guage for abstract data types and modules”. In Semantics ofData Types, LNCS 173. 6. Conclusion Springer-Verlag, 1984. Interfaces for object-oriented programming are a [BL881 K. Bruce and G. Longo. “A modest model of valuable addition to the paradigm. By using the interpre- records, inheritance and bounded quantifica- tation of interface as a type that formalizes the notion tion”. In Logic in Computer Science, 1988. of an object protocol it is possible to develop a rich sys- [Car841 L. Cardelli. “A semantics of multiple inher- tem of interfaces providing strong typing without com- itance”. In Semantics of Data Types, LNCS 173. Springer-Verlag, 1984.

466 OOPSLA ‘89 Proceedings October 1-6, 1989 [Car861 L. Cardelli. “Amber”. In Combinators and [GR831 A. Goldberg and D. Robson. Smalltalk-80: Functional Programming Languages, LNCS The Language and Its Implementation. Addi- 242. Springer-Verlag, 1986. son-Wesley, 1983. [Car881 L. Cardelli. “Structural subtyping and the [GHW85] J. Guttag, J. Homing, J. Wing. “Larch in notion of power type”. In ACM Symposium five easy pieces”. Technical Report 5, Digital on Principles of Programming Languages, Equipment Corp. - SystemsResearch Center, 1988. 1985. !KHl W. Cook, P. Canning, and W. Hill. [HMT88] R. Harper, R. Mimer, M. Tofte. “The Defi- “Inheritance in strongly-typed object-orient- nition of Standard ML, Version 2”. LFCS ed programming”. In preparation. Report, University of Edinburgh, 1988. [CCH891 P. Canning, W. Cook, W. Hill, W. Olthoff, [JGZ88] R. Johnson, J. Graver, and L. Zurawski. and J. Mitchell. “F-Bounded quantification “TS: An optimizing compiler for Small- for object-oriented programming”. In Func- taW. In Object-Oriented Programming Sys- tional Programming Languages and Computer tems, Languages, and Applications, 1988. Architectures, 1989. [JMSS] L. Jategaonkar and 3. Mitchell. “ML with [CDK891 L. Cardelli, J. Donahue, B. Kaslow, and G. extended pattern matching and subtypes”. In Nelson. “The Modula-3 type system”. In Lisp and Functional Programming, 1988. ACM Symposium on Principles of Program- ILie H. Lieberman. “Using prototypical objects ming Languages, 1989. to implement shared behavior in an object- [CHOSS] P. Canning, W. Hill, and W. Olthoff. oriented System”. In Object-Oriented Pro- “Towards a kernel language for object-ori- gramming Systems, Languages, and Applica- ented programming”. Technical Report STL- tions, 1986. 88-21, Hewlett-Packard Laboratories, 1988. [Mey87] B. Meyer. Object-Oriented Software Con- [CM881 L. Cardelli and J. Mitchell. “Semantic meth- struction. Prentice-Hall, 1987. ods for object-oriented languages”, part 2. t’Red881 U. Reddy. “Objects as closures: abstract se- OOPSLA’88 Tutorial on Semantics of Inher- mantics of object oriented languages”. In itance. Lisp and Functional Programming, 1988. [Coo89] W. R. Cook. “A proposal for making Eiffel lRey741 J. Reynolds. “Towards a theory of type type-safe”. In European Conference on Ob- structure”. In J. Loeckx, ed., Conference on ject-oriented Programming, 1989. Programming. Springer-Verlag, New York, [Coo89a] W. R. Cook. “A denotational semantics of 1974. inheritance”. Ph. D. Thesis, Brown Universi- [SCBSS] C. Schaffert, T. Cooper, B. Bullis. “An in- ty, 1989. troduction to Trellis/Owl”. Object-Orient- [CP89] W. R. Cook and J. Palsberg. “A denotation- ed Programming Systems, Languages, and Ap- al model of inheritance and its correctness”. plications, 1986. Jn Object-Oriented Programming Systems, rSny861 A. Snyder. “Encapsulation and inheritance in Languages, and Applications, 1989 . object-oriented programming languages”. In [CW85] L. Cardelli and P. Wegner. “On understand- Object-Oriented Programming Systems, Lan- ing types, data abstraction, and polymor- guages, and Applications, 1986. phism”. Computing Surveys, 17(4):471-522, [St&61 B. Stroustrup. The C+ + Programming Lan- 1985. guage. Addison-Wesley, 1986. [DOD831 U. S. Department of Defense. Reference lWan891 M. Wand. “Type inference for record concat- Manualfor the Ada Programming Language. enation and inheritance”. In Logic in Comput- 1983. er Science, 1989. lEM851 H. Ehrig and B. Mahr. Fundamentals ofAl- gebraic Specification 1. Springer-Verlag, 1985. [Gir72] J-Y. Girard. “Interpretation fonctionelle et elimination des coupres de l’arithmetique d’order superieur”. These d’Etat, Paris, 1972.

October 1-6, 1989 OOPSLA ‘89 Proceedings 467