F-Bounded Polymorphism for Object-Oriented Programming

Total Page:16

File Type:pdf, Size:1020Kb

F-Bounded Polymorphism for Object-Oriented Programming F-Bounded Polymorphism for Object-Oriented Programming Peter Canning, William Cook, Walter Hill, Walter Oltho® Hewlett-Packard Laboratories P.O. Box 10490, Palo Alto, CA 94303-0971 John C. Mitchell Department of Computer Science Stanford University, Stanford, CA 94309 Abstract ing was identi¯ed as an important form of polymor- phism in object-oriented programs. This lead to the Bounded quanti¯cation was introduced by Cardelli and development of \bounded quanti¯cation" in [7]. If we Wegner as a means of typing functions that operate uni- view objects as elements of non-recursive record types, formly over all subtypes of a given type. They de¯ned then bounded quanti¯cation provides a useful form of a simple \object" model and used bounded quanti¯ca- polymorphism over objects. However, a more sophis- tion to type-check functions that make sense on all ob- ticated presentation of object-oriented constructs (as jects having a speci¯ed set of \attributes." A more re- in [5, 11, 10]) would allow objects that are elements alistic presentation of object-oriented languages would of recursively-de¯ned types. With recursive types, the allow objects that are elements of recursively-de¯ned Cardelli-Wegner form of bounded quanti¯cation is not types. In this context, bounded quanti¯cation no longer su±ciently expressive to meet its original goal. serves its intended purpose. It is easy to ¯nd func- F-bounded quanti¯cation is a natural extension of tions that makes sense on all objects having a speci- bounded quanti¯cation that seems particularly useful ¯ed set of methods, but which cannot be typed in the in connection with recursive types. The essential idea Cardelli-Wegner system. To provide a basis for typed may be illustrated by comparison with Cardelli-Wegner polymorphic functions in object-oriented languages, we bounded quanti¯cation. Using \⊆" for the subtype re- introduce F-bounded quanti¯cation. Some applications lation, a simple example of a bounded-quanti¯ed type of F-bounded quanti¯cation are presented and seman- is the type 8t ⊆ ¿: t ! t. This is the type of func- tic issues are discussed. Although our original moti- tions which map t to t, for every subtype t of ¿. In vation was to type polymorphic functions over objects, a setting where all structurally similar objects belong F-bounded quanti¯cation is a general form of polymor- to subtypes of a given type, many useful polymorphic phism that seems useful whenever recursive type de¯n- functions will have bounded quanti¯ed types. For ex- itions and subtyping are used. ample, if we type an object by listing its methods and their types, an object with a print method may have type f:::; print: void ! string;:::g, indicating that the 1 Introduction method print produces a print representation of the object. In the view of subtyping presented in [8], Although object-oriented programming has attracted every type of this form will be a subtype of the type increasing interest in recent years, the development fprint: void ! stringg of objects having only a print of polymorphic type systems for object-oriented lan- method. For example, guages has progressed slowly. One reason is that object- oriented languages are often described using terminol- fA: int ! void; print: void ! stringg ogy that sets them apart from functional languages. In ⊆ fprint: void ! stringg: addition, there has been a lack of formal models for object-oriented languages. As a result, it has been A function taking a list of printable objects, a string and di±cult to see how practical polymorphic type sys- returning an object whose print representation matches tems should be adapted for typing object-oriented con- the given string will have the bounded-quanti¯ed type structs. In Cardelli's seminal paper [8], record subtyp- 8t ⊆ fprint: stringg: list[t] ! string ! t. 1 The flexibility of bounded quanti¯cation is dramati- may be imposed on the quanti¯ed type variable. Thus cally reduced when objects belong to recursively-de¯ned Curtis' system subsumes our more modest proposal. types. For example, consider the type However, we believe that our form of quanti¯cation is both su±cient to type-check practically useful object- PartialOrder = f lesseq: PartialOrder ! Bool g. oriented programs, and more tractable. Some evidence for the naturality of F-bounded quanti¯cation is the Each object of this type has a method lesseq which may intriguing connection with F-coalgebras, the dual of a be applied to another object of the same type. We in- standard construction in the category-theoretic charac- tend the result of x:lesseq(y) to be true if x does not terization of type recursion [22]. exceed y in some ordering, and false otherwise. Using The next section surveys relevant background on lesseq, it should be possible to sort lists of PartialOrder strongly-typed object-oriented programming. Section 3 elements, for example. We may easily write a sort- illustrates in detail problems with previous techniques ing function with type 8t ⊆ PartialOrder: list[t] ! list[t]. for dealing with recursive object types. Section 4 intro- However, as we shall see later in the paper, object- duces F-bounded quanti¯cation and demonstrates that oriented versions of the usual partially-ordered types it solves the typing problems presented in the previous such as integers are not subtypes of PartialOrder. There- section. some speculative observations on the semantic fore, our generic sorting function cannot be used in the aspects of F-bounded quanti¯cation. Section 6 summa- way we might expect. To solve this problem and related rizes our contribution and indicates directions for future di±culties with other forms of recursive types we intro- research. duce a generalization of bounded quanti¯cation which we call F-bounded quanti¯cation, for want of better ter- minology. For the example at hand, consider the func- 2 Background tion F from types to types given by 2.1 Objects, Records and Recursive F[t] = f lesseq: t ! bool g. Types We may write a polymorphic sorting function of type A fundamental premise underlying most models of 8t ⊆ F[t]:list[t] ! list[t], where this function is de¯ned on object-oriented programming is that objects may be re- any type t such that t ⊆ F[t]. Since integer ⊆ F[integer], garded as record whose components are functions rep- as explained in Section 3.3, we may apply such a sorting resenting methods [8, 7, 25, 11, 5]. In this model, \mes- function to lists of integers or lists of any other type of sage sending" is implemented by simple component se- objects having lesseq methods. lection. One practical application of F-bounded quanti¯cation Record types are used to describe the protocols [14] is for understanding some problems in the type system or interfaces of objects. A record type is a map- of the Ei®el programming language [18]. Ei®el intro- ping of labels to types. A record consisting of labels duces a special type expression, like Current, to represent l1; : : : ; lj with associated values in types σ1; : : : ; σj has recursion at the type level. Like Current always repre- type fl1: σ1; : : : ; lj: σjg. The ¯elds of the record type sents the `current class': in a class P it simply stands describe messages together with the types of their ar- for P , but when this class is inherited by a subclass C, guments and return values. This view is adopted in the like Current in an inherited attribute is reinterpreted to programming languages Amber [6], Modula-3 [10], and stand for the subclass C. The subclasses of such a class TS [17]. are usefully understood as having interfaces that sat- Even the very simplest \textbook" examples isfy an F-bound. However, as mentioned above, there from object-oriented programming produce recursively- is no necessary subtype relation among types satisfying de¯ned record types [21, 1, 6, 16, 10]. For example, an F-bound. This analysis explains some insecurities in the type of a planar point with four methods is de¯ned the Ei®el type-system, which always allows subclasses recursively as follows. to act as if they are subtypes of their parents. Further Point = f details are given in [12], along with some suggestions for x : void ! Real, correcting Ei®el's problems using the results in this pa- y : void ! Real, per. The error in the Ei®el type system illustrates the move : Real £ Real ! Point, subtlety involved in designing flexible and sound type equal : Point ! Boolean systems for object-oriented languages. g Another type system with a generalized form of bounded quanti¯cation is presented by Curtis [13]. In The body of the recursive type is a record type indi- this system, arbitrary collections of subtype constraints cated by braces f:::g. The use of Point in the return 2 type of move indicates that the move method returns This means, informally, that if assuming s is a sub- an object that has the same type as the original point. type of t allows one to prove that σ is a subtype of ¿, Its use as the argument type of equal indicates that the then the recursive type Rec s: σ is a subtype of Rec t: ¿. equal method takes an argument with the same type. For example, the following type is a supertype of Point: In other words, equal is a `binary' operation on points, viz. for two points p and q, the expression p.equal(q) is Movable = Rec mv. f move : Real £ Real ! mv g meaningful. because the body of Point is a subtype of the body of A useful notation for recursively de¯ned types is the Movable, given the assumption pnt ⊆ mv: form Rec t:A .
Recommended publications
  • An Extended Theory of Primitive Objects: First Order System Luigi Liquori
    An extended Theory of Primitive Objects: First order system Luigi Liquori To cite this version: Luigi Liquori. An extended Theory of Primitive Objects: First order system. ECOOP, Jun 1997, Jyvaskyla, Finland. pp.146-169, 10.1007/BFb0053378. hal-01154568 HAL Id: hal-01154568 https://hal.inria.fr/hal-01154568 Submitted on 22 May 2015 HAL is a multi-disciplinary open access L’archive ouverte pluridisciplinaire HAL, est archive for the deposit and dissemination of sci- destinée au dépôt et à la diffusion de documents entific research documents, whether they are pub- scientifiques de niveau recherche, publiés ou non, lished or not. The documents may come from émanant des établissements d’enseignement et de teaching and research institutions in France or recherche français ou étrangers, des laboratoires abroad, or from public or private research centers. publics ou privés. An Extended Theory of Primitive Objects: First Order System Luigi Liquori ? Dip. Informatica, Universit`adi Torino, C.so Svizzera 185, I-10149 Torino, Italy e-mail: [email protected] Abstract. We investigate a first-order extension of the Theory of Prim- itive Objects of [5] that supports method extension in presence of object subsumption. Extension is the ability of modifying the behavior of an ob- ject by adding new methods (and inheriting the existing ones). Object subsumption allows to use objects with a bigger interface in a context expecting another object with a smaller interface. This extended calcu- lus has a sound type system which allows static detection of run-time errors such as message-not-understood, \width" subtyping and a typed equational theory on objects.
    [Show full text]
  • On Model Subtyping Cl´Ement Guy, Benoit Combemale, Steven Derrien, James Steel, Jean-Marc J´Ez´Equel
    View metadata, citation and similar papers at core.ac.uk brought to you by CORE provided by HAL-Rennes 1 On Model Subtyping Cl´ement Guy, Benoit Combemale, Steven Derrien, James Steel, Jean-Marc J´ez´equel To cite this version: Cl´ement Guy, Benoit Combemale, Steven Derrien, James Steel, Jean-Marc J´ez´equel.On Model Subtyping. ECMFA - 8th European Conference on Modelling Foundations and Applications, Jul 2012, Kgs. Lyngby, Denmark. 2012. <hal-00695034> HAL Id: hal-00695034 https://hal.inria.fr/hal-00695034 Submitted on 7 May 2012 HAL is a multi-disciplinary open access L'archive ouverte pluridisciplinaire HAL, est archive for the deposit and dissemination of sci- destin´eeau d´ep^otet `ala diffusion de documents entific research documents, whether they are pub- scientifiques de niveau recherche, publi´esou non, lished or not. The documents may come from ´emanant des ´etablissements d'enseignement et de teaching and research institutions in France or recherche fran¸caisou ´etrangers,des laboratoires abroad, or from public or private research centers. publics ou priv´es. On Model Subtyping Clément Guy1, Benoit Combemale1, Steven Derrien1, Jim R. H. Steel2, and Jean-Marc Jézéquel1 1 University of Rennes1, IRISA/INRIA, France 2 University of Queensland, Australia Abstract. Various approaches have recently been proposed to ease the manipu- lation of models for specific purposes (e.g., automatic model adaptation or reuse of model transformations). Such approaches raise the need for a unified theory that would ease their combination, but would also outline the scope of what can be expected in terms of engineering to put model manipulation into action.
    [Show full text]
  • Design and Implementation of Generics for the .NET Common Language Runtime
    Design and Implementation of Generics for the .NET Common Language Runtime Andrew Kennedy Don Syme Microsoft Research, Cambridge, U.K. fakeÒÒ¸d×ÝÑeg@ÑicÖÓ×ÓfغcÓÑ Abstract cally through an interface definition language, or IDL) that is nec- essary for language interoperation. The Microsoft .NET Common Language Runtime provides a This paper describes the design and implementation of support shared type system, intermediate language and dynamic execution for parametric polymorphism in the CLR. In its initial release, the environment for the implementation and inter-operation of multiple CLR has no support for polymorphism, an omission shared by the source languages. In this paper we extend it with direct support for JVM. Of course, it is always possible to “compile away” polymor- parametric polymorphism (also known as generics), describing the phism by translation, as has been demonstrated in a number of ex- design through examples written in an extended version of the C# tensions to Java [14, 4, 6, 13, 2, 16] that require no change to the programming language, and explaining aspects of implementation JVM, and in compilers for polymorphic languages that target the by reference to a prototype extension to the runtime. JVM or CLR (MLj [3], Haskell, Eiffel, Mercury). However, such Our design is very expressive, supporting parameterized types, systems inevitably suffer drawbacks of some kind, whether through polymorphic static, instance and virtual methods, “F-bounded” source language restrictions (disallowing primitive type instanti- type parameters, instantiation at pointer and value types, polymor- ations to enable a simple erasure-based translation, as in GJ and phic recursion, and exact run-time types.
    [Show full text]
  • Subtyping Recursive Types
    ACM Transactions on Programming Languages and Systems, 15(4), pp. 575-631, 1993. Subtyping Recursive Types Roberto M. Amadio1 Luca Cardelli CNRS-CRIN, Nancy DEC, Systems Research Center Abstract We investigate the interactions of subtyping and recursive types, in a simply typed λ-calculus. The two fundamental questions here are whether two (recursive) types are in the subtype relation, and whether a term has a type. To address the first question, we relate various definitions of type equivalence and subtyping that are induced by a model, an ordering on infinite trees, an algorithm, and a set of type rules. We show soundness and completeness between the rules, the algorithm, and the tree semantics. We also prove soundness and a restricted form of completeness for the model. To address the second question, we show that to every pair of types in the subtype relation we can associate a term whose denotation is the uniquely determined coercion map between the two types. Moreover, we derive an algorithm that, when given a term with implicit coercions, can infer its least type whenever possible. 1This author's work has been supported in part by Digital Equipment Corporation and in part by the Stanford-CNR Collaboration Project. Page 1 Contents 1. Introduction 1.1 Types 1.2 Subtypes 1.3 Equality of Recursive Types 1.4 Subtyping of Recursive Types 1.5 Algorithm outline 1.6 Formal development 2. A Simply Typed λ-calculus with Recursive Types 2.1 Types 2.2 Terms 2.3 Equations 3. Tree Ordering 3.1 Subtyping Non-recursive Types 3.2 Folding and Unfolding 3.3 Tree Expansion 3.4 Finite Approximations 4.
    [Show full text]
  • 13 Templates-Generics.Pdf
    CS 242 2012 Generic programming in OO Languages Reading Text: Sections 9.4.1 and 9.4.3 J Koskinen, Metaprogramming in C++, Sections 2 – 5 Gilad Bracha, Generics in the Java Programming Language Questions • If subtyping and inheritance are so great, why do we need type parameterization in object- oriented languages? • The great polymorphism debate – Subtype polymorphism • Apply f(Object x) to any y : C <: Object – Parametric polymorphism • Apply generic <T> f(T x) to any y : C Do these serve similar or different purposes? Outline • C++ Templates – Polymorphism vs Overloading – C++ Template specialization – Example: Standard Template Library (STL) – C++ Template metaprogramming • Java Generics – Subtyping versus generics – Static type checking for generics – Implementation of Java generics Polymorphism vs Overloading • Parametric polymorphism – Single algorithm may be given many types – Type variable may be replaced by any type – f :: tt => f :: IntInt, f :: BoolBool, ... • Overloading – A single symbol may refer to more than one algorithm – Each algorithm may have different type – Choice of algorithm determined by type context – Types of symbol may be arbitrarily different – + has types int*intint, real*realreal, ... Polymorphism: Haskell vs C++ • Haskell polymorphic function – Declarations (generally) require no type information – Type inference uses type variables – Type inference substitutes for variables as needed to instantiate polymorphic code • C++ function template – Programmer declares argument, result types of fctns – Programmers
    [Show full text]
  • On the Interaction of Object-Oriented Design Patterns and Programming
    On the Interaction of Object-Oriented Design Patterns and Programming Languages Gerald Baumgartner∗ Konstantin L¨aufer∗∗ Vincent F. Russo∗∗∗ ∗ Department of Computer and Information Science The Ohio State University 395 Dreese Lab., 2015 Neil Ave. Columbus, OH 43210–1277, USA [email protected] ∗∗ Department of Mathematical and Computer Sciences Loyola University Chicago 6525 N. Sheridan Rd. Chicago, IL 60626, USA [email protected] ∗∗∗ Lycos, Inc. 400–2 Totten Pond Rd. Waltham, MA 02154, USA [email protected] February 29, 1996 Abstract Design patterns are distilled from many real systems to catalog common programming practice. However, some object-oriented design patterns are distorted or overly complicated because of the lack of supporting programming language constructs or mechanisms. For this paper, we have analyzed several published design patterns looking for idiomatic ways of working around constraints of the implemen- tation language. From this analysis, we lay a groundwork of general-purpose language constructs and mechanisms that, if provided by a statically typed, object-oriented language, would better support the arXiv:1905.13674v1 [cs.PL] 31 May 2019 implementation of design patterns and, transitively, benefit the construction of many real systems. In particular, our catalog of language constructs includes subtyping separate from inheritance, lexically scoped closure objects independent of classes, and multimethod dispatch. The proposed constructs and mechanisms are not radically new, but rather are adopted from a variety of languages and programming language research and combined in a new, orthogonal manner. We argue that by describing design pat- terns in terms of the proposed constructs and mechanisms, pattern descriptions become simpler and, therefore, accessible to a larger number of language communities.
    [Show full text]
  • Orthogonal to the Java Imperative?
    Orthogonal to the Java Imperative? Suad Alagi´c, Jose Solorzano, and David Gitchell Department of Computer Science, Wichita State University Wichita, KS 67260-0083, USA [email protected] Abstract. Three nontrivial limitations of the existing JavaTM technol- ogy are considered from the viewpoint of object-oriented database tech- nology. The limitations are: lack of support for orthogonal persistence, lack of parametric (and in fact bounded and F-bounded) polymorphism and lack of an assertion (constraint) language. These limitations are over- come by leaving Java as it is, and developing a declarative (query in par- ticular) component of the Java technology. This declarative language is implemented on top of the Java Virtual Machine, extended with orthog- onal and transitive persistence. The model of persistence also features complex name space management. Keywords: Declarative languages, orthogonal persistence, F-bounded polymorphism, Java Virtual Machine. 1 Introduction In spite of the fact that JavaTM [17] is a product of good language design, it exhibits several serious limitations with respect to object-oriented database management. A perfectly valid justification is that it was probably never con- ceived as a database programming language. Yet, some of these database-critical features are important for object-oriented programming in general. The first such limitation is, of course, the lack of support for persistence. Persistence is a key feature of object-oriented database technology [10]. The second limitation is the absence of parametric polymorphism. This lim- itation is particularly critical in database management because most database technologies rely heavily on collections. Static typing of collections in Java is impossible, and so is static typing of queries.
    [Show full text]
  • A Core Calculus of Metaclasses
    A Core Calculus of Metaclasses Sam Tobin-Hochstadt Eric Allen Northeastern University Sun Microsystems Laboratories [email protected] [email protected] Abstract see the problem, consider a system with a class Eagle and Metaclasses provide a useful mechanism for abstraction in an instance Harry. The static type system can ensure that object-oriented languages. But most languages that support any messages that Harry responds to are also understood by metaclasses impose severe restrictions on their use. Typi- any other instance of Eagle. cally, a metaclass is allowed to have only a single instance However, even in a language where classes can have static and all metaclasses are required to share a common super- methods, the desired relationships cannot be expressed. For class [6]. In addition, few languages that support metaclasses example, in such a language, we can write the expression include a static type system, and none include a type system Eagle.isEndangered() provided that Eagle has the ap- with nominal subtyping (i.e., subtyping as defined in lan- propriate static method. Such a method is appropriate for guages such as the JavaTM Programming Language or C#). any class that is a species. However, if Salmon is another To elucidate the structure of metaclasses and their rela- class in our system, our type system provides us no way of tionship with static types, we present a core calculus for a requiring that it also have an isEndangered method. This nominally typed object-oriented language with metaclasses is because we cannot classify both Salmon and Eagle, when and prove type soundness over this core.
    [Show full text]
  • Polymorphic Subtyping in O'haskell
    Science of Computer Programming 43 (2002) 93–127 www.elsevier.com/locate/scico Polymorphic subtyping in O’Haskell Johan Nordlander Department of Computer Science and Engineering, Oregon Graduate Institute of Science and Technology, 20000 NW Walker Road, Beaverton, OR 97006, USA Abstract O’Haskell is a programming language derived from Haskell by the addition of concurrent reactive objects and subtyping. Because Haskell already encompasses an advanced type system with polymorphism and overloading, the type system of O’Haskell is much richer than what is the norm in almost any widespread object-oriented or functional language. Yet, there is strong evidence that O’Haskell is not a complex language to use, and that both Java and Haskell pro- grammers can easily ÿnd their way with its polymorphic subtyping system. This paper describes the type system of O’Haskell both formally and from a programmer’s point of view; the latter task is accomplished with the aid of an illustrative, real-world programming example: a strongly typed interface to the graphical toolkit Tk. c 2002 Elsevier Science B.V. All rights reserved. Keywords: Type inference; Subtyping; Polymorphism; Haskell; Graphical toolkit 1. Introduction The programming language O’Haskell is the result of a ÿnely tuned combination of ideas and concepts from functional, object-oriented, and concurrent programming, that has its origin in the purely functional language Haskell [36]. The name O’Haskell is a tribute to this parentage, where the O should be read as an indication of Objects,as well as a reactive breach with the tradition that views Input as an active operation on par with Output.
    [Show full text]
  • CS 6110 S18 Lecture 23 Subtyping 1 Introduction 2 Basic Subtyping Rules
    CS 6110 S18 Lecture 23 Subtyping 1 Introduction In this lecture, we attempt to extend the typed λ-calculus to support objects. In particular, we explore the concept of subtyping in detail, which is one of the key features of object-oriented (OO) languages. Subtyping was first introduced in Simula, the first object-oriented programming language. Its inventors Ole-Johan Dahl and Kristen Nygaard later went on to win the Turing award for their contribution to the field of object-oriented programming. Simula introduced a number of innovative features that have become the mainstay of modern OO languages including objects, subtyping and inheritance. The concept of subtyping is closely tied to inheritance and polymorphism and offers a formal way of studying them. It is best illustrated by means of an example. This is an example of a hierarchy that describes a Person Student Staff Grad Undergrad TA RA Figure 1: A Subtype Hierarchy subtype relationship between different types. In this case, the types Student and Staff are both subtypes of Person. Alternatively, one can say that Person is a supertype of Student and Staff. Similarly, TA is a subtype of the Student and Person types, and so on. The subtype relationship is normally a preorder (reflexive and transitive) on types. A subtype relationship can also be viewed in terms of subsets. If σ is a subtype of τ, then all elements of type σ are automatically elements of type τ. The ≤ symbol is typically used to denote the subtype relationship. Thus, Staff ≤ Person, RA ≤ Student, etc. Sometimes the symbol <: is used, but we will stick with ≤.
    [Show full text]
  • Structural Model Subtyping with OCL Constraints
    Structural Model Subtyping with OCL Constraints Artur Boronat Department of Informatics University of Leicester United Kingdom [email protected] Abstract 1 Introduction In model-driven engineering (MDE), models abstract the rel- Our aim in this work is to revisit the research question of evant features of software artefacts and model management whether type subsumption − i.e. the relation capturing that operations, including model transformations, act on them any inhabitant of a given subtype is also an inhabitant of a automating large tasks of the development process. Flexible given supertype − is a valid mechanism for facilitating reuse reuse of such operations is an important factor to improve of model management operations in MDE in order to analyse productivity when developing and maintaining MDE solu- its advantages and limitations. We approach this topic by tions. In this work, we revisit the traditional notion of object exposing a general problem involving reuse, which we then subtyping based on subsumption, discarded by other ap- solve by using structural model subtyping. proaches to model subtyping. We refine a type system for In a typed setting, model management operations are ap- object-oriented programming, with multiple inheritance, to plied to models that conform to metamodels, which define support model types in order to analyse its advantages and the abstract syntax of a modeling language. Additional well- limitations with respect to reuse in MDE. Specifically, we ex- formedness constraints can be added to the language, usually tend type expressions with referential constraints and with by encoding them in an OCL dialect. The notion of a pair OCL constraints.
    [Show full text]
  • CSCE 314 Programming Languages Java Generics II
    CSCE 314 Programming Languages ! Java Generics II Dr. Hyunyoung Lee ! ! ! !1 Lee CSCE 314 TAMU Type System and Variance Within the type system of a programming language, variance refers to how subtyping between complex types (e.g., list of Cats versus list of Animals, and function returning Cat versus function returning Animal) relates to subtyping between their components (e.g., Cats and Animals). !2 Lee CSCE 314 TAMU Covariance and Contravariance Within the type system of a programming language, a typing rule or a type constructor is: covariant if it preserves the ordering ≤ of types, which orders types from more specific to more generic contravariant if it reverses this ordering invariant if neither of these applies. !3 Lee CSCE 314 TAMU Co/Contravariance Idea Read-only data types can be covariant; Write-only data types can be contravariant; Mutable data types which support read and write operations should be invariant. ! Even though Java arrays are a mutable data type, Java treats array types covariantly, by marking each array object with a type when it is created. !4 Lee CSCE 314 TAMU Covariant Method Return Type Return types of methods in Java can be covariant: class Animal { . public Animal clone() { return new Animal(); } } class Panda extends Animal { . public Panda clone() { return new Panda(); } } This is safe - whenever we call Animal’s clone(), we get at least an Animal, but possibly something more (a subtype of Animal) Animal p = new Panda(); . Animal a = p.clone(); // returns a Panda, OK !5 Lee CSCE 314 TAMU Covariant Method Argument Type (Bad Idea) Would this be a good idea? class Animal { .
    [Show full text]