Polymorphism

Total Page:16

File Type:pdf, Size:1020Kb

Polymorphism Polymorphism CMSC 330: Organization of Definition Programming Languages • Feature that allows values of different data types to be handled using a uniform interface Applicable to • Functions ! Same function applied to different data types Polymorphism ! Example let id = function x -> x • Data types ! Same data type can contain different data types ! Example type a option = None CMSC 330 | Some of a 2 Two Kinds of Polymorphism Polymorphism Overview Described by Strachey in 1967 Subtype (for OO languages) Ad hoc and Subtype polymorphism • Sometimes considered ad-hoc • Range of types is finite Ad-hoc • Combinations must be specified in advance • Overloading • Behavior may differ based on type of arguments ! Operator overloading ! Method name overloading Parametric polymorphism • Code written without mention of specific type Parametric ML types • May be transparently used with arbitrary # of types • • Behavior is same for different types of arguments • A.k.a. generic programming (for OO languages) ! Bounded parametric polymorphism combines subtype and parametric polymorphism CMSC 330 3 CMSC 330 4 Subtype Polymorphism Subtype Polymorphism Any context expecting an object of type A can be More generally, B is a subtype of A if it can “do” given an object of type B where B is a subtype of A everything A can • Example: Function parameter has type A • Has the “same” fields, methods • So it may be called with arguments of type B Java interfaces also support subtyping Subtyping enabled by inheritance interface A { … } class B implements A { … } class A { … } class C implements A { … } class B extends A { … } // subclass static void f(A arg) { … } static void f(A arg) { … } B b = new B(); A a = new A(); C c = new C(); B b = new B(); f(b); f(c); // f accepts arg of type B or C f(a); f(b); // f accepts arg of type A or B CMSC 330 5 CMSC 330 6 When can we extend or implement? Overloading When can A extend B? Multiple copies of function • Complicated! • Same function name • Roughly: When it overrides methods such that the • But different number / type of parameters overriding types are subtypes of original Arguments determine function actually invoked When can A implement B? • Function is uniquely identified not by function name, • When it has methods whose types are the same as but by name + order & number of argument type(s) those required by the interface ! print(Integer i) → print_Integer(…) ! print(Float f) → print_Float(…) static void print(Integer arg) { … } static void print(Float arg) { … } print(1); // invokes 1st print print(3.14); // invokes 2nd print CMSC 330 7 CMSC 330 8 Overloading and Overriding Operator Overloading Interaction is confusing Treat operators as functions • Common mistake is inadvertently overload when you • With special syntax for invocations mean to override • Behavior different depending on operand type public class Point { private int x = 0, y = 0; public boolean equals(Point p) { //overloads Example return (p.x == x) && (p.y == y); } • + in Java public static void main(String args[]) { Point p1 = new Point(); 1 + 2 // integer addition Point p2 = new Point(); 1.0 + 3.14 // float addition Object o = p1; // string concatenation System.out.println(o.equals(p2)); //prints false Hello + world System.out.println(p1.equals(p2)); //prints true } } CMSC 330 9 CMSC 330 10 Operator Overloading (cont.) Parametric Polymorphism User-specified operator overloading Found in statically typed functional languages • Supported in languages such as Ruby, C++ • OCaml, ML, Haskell • Makes user data types appear more like native types • Example Examples let hd = function (h::_) -> h a list -> a • Defining function for ^ operator Also used in object oriented programming class MyS class MyS { def ^ (arg) MyS operator^(MyS arg){ • Known as generic programming ... ... • Example: Java, C++ end } end } Ruby C++ CMSC 330 11 CMSC 330 12 An Integer Stack Implementation Integer Stack Client class Stack { class Entry { Integer elt; Entry next; Stack is = new Stack(); Entry(Integer i, Entry n) { elt = i; next = n; } Integer i; } is.push(new Integer(3)); Entry theStack; is.push(new Integer(4)); void push(Integer i) { theStack = new Entry(i, theStack); i = is.pop(); } Integer pop() throws EmptyStackException { if (theStack == null) If we also want a stack of Floats, do we throw new EmptyStackException(); need to write a Float Stack class? else { Integer i = theStack.elt; theStack = theStack.next; return i; }}} CMSC 330 13 CMSC 330 14 An Object Stack Implementation New Stack Client class Stack { Stack is = new Stack(); class Entry { Object elt; Entry next; Integer i; Entry(Object i, Entry n) { elt = i; next = n; } is.push(new Integer(3)); } is.push(new Integer(4)); Entry theStack; void push(Object i) { i = (Integer) is.pop(); theStack = new Entry(i, theStack); Object stacks are polymorphic & reusable } Object pop() throws EmptyStackException { • push() works the same if (theStack == null) throw new EmptyStackException(); • But now pop() returns an Object else { ! Object i = theStack.elt; Have to downcast back to Integer theStack = theStack.next; • Not checked until run-time return i; }}} CMSC 330 15 CMSC 330 16 General Problem Parametric Polymorphism (for Classes) When we move from an X container to an Java 1.5 introduced generics Object container We can parameterize the Stack class by its • Methods that take Xs as input parameters are OK element type ! If youre allowed to pass Object in, you can pass any X in • Methods that return Xs as results require downcasts ! You only get Objects out, which you need to cast down to X Syntax • Class declaration: class A<T> { ... } ! A is the class name, as before General characteristic of subtype polymorphism ! T is a type variable, can be used in body of class (...) • Client usage declaration: A<Integer> x; ! We instantiate A with the Integer type CMSC 330 17 CMSC 330 18 Parametric Polymorphism for Stack Stack<Element> Client class Stack<ElementType> { class Entry { ElementType elt; Entry next; Stack<Integer> is = new Stack<Integer>(); Entry(ElementType i, Entry n) { elt = i; next = Integer i; n; } is.push(new Integer(3)); } is.push(new Integer(4)); Entry theStack; i = is.pop(); void push(ElementType i) { theStack = new Entry(i, theStack); No downcasts } ElementType pop() throws EmptyStackException { Type-checked at compile time if (theStack == null) No need to duplicate Stack code for every usage throw new EmptyStackException(); else { • line i = is.pop(); can stay the same even if the type of is isnt an ElementType i = theStack.elt; integer in every path through the program theStack = theStack.next; return i; }}} CMSC 330 19 CMSC 330 20 Parametric Polymorphism for Methods Parametric Polymorphism, Again String is a subtype of Object But id() doesnt care about the type of x 1. static Object id(Object x) { return x; } • It works for any type 2. static Object id(String x) { return x; } 3. static String id(Object x) { return x; } So parameterize the static method 4. static String id(String x) { return x; } static <T> T id(T x) { return x; } Integer i = id(new Integer(3)); Cant pass an Object to 2 or 4 3 doesnt type check • Notice no need to instantiate id; compiler figures out Can pass a String to 1 but you get an Object back the correct type at usage • The formal parameter has type T, the actual parameter has type Integer CMSC 330 21 CMSC 330 22 Standard Library, and Java 1.5 (and later) Translation via Erasure Part of Java 1.5 (called generics) Replace uses of type variables with Object • Comes with replacement for java.util.* • class A<T> { ...T x;... } becomes ! class LinkedList<A> { ...} • class A { ...Object x;... } ! class HashMap<A, B> { ... } Add downcasts wherever necessary ! interface Collection<A> { ... } • Excellent tutorial listed on references page • Integer x = A<Integer>.get(); becomes • Integer x = (Integer) (A.get()); But they didnt change the JVM to add generics So why did we bother with generics if theyre • How was that done? just going to be removed? • Because the compiler still did type checking for us • We know that those casts will not fail at run time CMSC 330 23 CMSC 330 24 Limitations of Translation Using with Legacy Code Some type information not available at compile- Translation via type erasure time • class A <T> becomes class A • Recall type variables T are rewritten to Object Thus class A is available as a raw type Disallowed, assuming T is type variable • class A<T> { ... } • new T() would translate to new Object() (error) • class B { A x; } // use A as raw type • new T[n] would translate to new Object[n] (warning) • Some casts/instanceofs that use T Sometimes useful with legacy code, but... ! Only ones the compiler can figure out are allowed • Dangerous feature to use, plus unsafe • Relies on implementation of generics, not semantics CMSC 330 25 CMSC 330 26 Subtyping and Arrays Problem with Subtyping Arrays public class A { ... } Java has one funny subtyping feature public class B extends A { void newMethod(); } • If S is a subtype of T, then ... • S[ ] is a subtype of T[ ] void foo(void) { B[] bs = new B[3]; A[] as; Lets write methods that take arbitrary arrays as = bs; // Since B[] subtype of A[] public static void reverseArray(Object [] A) { as[0] = new A(); // (1) for(int i=0, j=A.length-1; i<j; i++,j--) { bs[0].newMethod(); // (2) Fails since not type B Object tmp = A[i]; } A[i] = A[j]; A[j] = tmp; Program compiles without warning } Java must generate run-time check at (1) to prevent (2) } • Type written to array must be subtype of array contents CMSC 330 27
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]
  • Parametric Polymorphism Parametric Polymorphism
    Parametric Polymorphism Parametric Polymorphism • is a way to make a language more expressive, while still maintaining full static type-safety (every Haskell expression has a type, and types are all checked at compile-time; programs with type errors will not even compile) • using parametric polymorphism, a function or a data type can be written generically so that it can handle values identically without depending on their type • such functions and data types are called generic functions and generic datatypes Polymorphism in Haskell • Two kinds of polymorphism in Haskell – parametric and ad hoc (coming later!) • Both kinds involve type variables, standing for arbitrary types. • Easy to spot because they start with lower case letters • Usually we just use one letter on its own, e.g. a, b, c • When we use a polymorphic function we will usually do so at a specific type, called an instance. The process is called instantiation. Identity function Consider the identity function: id x = x Prelude> :t id id :: a -> a It does not do anything with the input other than returning it, therefore it places no constraints on the input's type. Prelude> :t id id :: a -> a Prelude> id 3 3 Prelude> id "hello" "hello" Prelude> id 'c' 'c' Polymorphic datatypes • The identity function is the simplest possible polymorphic function but not very interesting • Most useful polymorphic functions involve polymorphic types • Notation – write the name(s) of the type variable(s) used to the left of the = symbol Maybe data Maybe a = Nothing | Just a • a is the type variable • When we instantiate a to something, e.g.
    [Show full text]
  • CSE 307: Principles of Programming Languages Classes and Inheritance
    OOP Introduction Type & Subtype Inheritance Overloading and Overriding CSE 307: Principles of Programming Languages Classes and Inheritance R. Sekar 1 / 52 OOP Introduction Type & Subtype Inheritance Overloading and Overriding Topics 1. OOP Introduction 3. Inheritance 2. Type & Subtype 4. Overloading and Overriding 2 / 52 OOP Introduction Type & Subtype Inheritance Overloading and Overriding Section 1 OOP Introduction 3 / 52 OOP Introduction Type & Subtype Inheritance Overloading and Overriding OOP (Object Oriented Programming) So far the languages that we encountered treat data and computation separately. In OOP, the data and computation are combined into an “object”. 4 / 52 OOP Introduction Type & Subtype Inheritance Overloading and Overriding Benefits of OOP more convenient: collects related information together, rather than distributing it. Example: C++ iostream class collects all I/O related operations together into one central place. Contrast with C I/O library, which consists of many distinct functions such as getchar, printf, scanf, sscanf, etc. centralizes and regulates access to data. If there is an error that corrupts object data, we need to look for the error only within its class Contrast with C programs, where access/modification code is distributed throughout the program 5 / 52 OOP Introduction Type & Subtype Inheritance Overloading and Overriding Benefits of OOP (Continued) Promotes reuse. by separating interface from implementation. We can replace the implementation of an object without changing client code. Contrast with C, where the implementation of a data structure such as a linked list is integrated into the client code by permitting extension of new objects via inheritance. Inheritance allows a new class to reuse the features of an existing class.
    [Show full text]
  • INF 102 CONCEPTS of PROG. LANGS Type Systems
    INF 102 CONCEPTS OF PROG. LANGS Type Systems Instructors: James Jones Copyright © Instructors. What is a Data Type? • A type is a collection of computational entities that share some common property • Programming languages are designed to help programmers organize computational constructs and use them correctly. Many programming languages organize data and computations into collections called types. • Some examples of types are: o the type Int of integers o the type (Int→Int) of functions from integers to integers Why do we need them? • Consider “untyped” universes: • Bit string in computer memory • λ-expressions in λ calculus • Sets in set theory • “untyped” = there’s only 1 type • Types arise naturally to categorize objects according to patterns of use • E.g. all integer numbers have same set of applicable operations Use of Types • Identifying and preventing meaningless errors in the program o Compile-time checking o Run-time checking • Program Organization and documentation o Separate types for separate concepts o Indicates intended use declared identifiers • Supports Optimization o Short integers require fewer bits o Access record component by known offset Type Errors • A type error occurs when a computational entity, such as a function or a data value, is used in a manner that is inconsistent with the concept it represents • Languages represent values as sequences of bits. A "type error" occurs when a bit sequence written for one type is used as a bit sequence for another type • A simple example can be assigning a string to an integer
    [Show full text]
  • Parametric Polymorphism (Generics) 30 April 2018 Lecturer: Andrew Myers
    CS 4120/5120 Lecture 36 Parametric Polymorphism (Generics) 30 April 2018 Lecturer: Andrew Myers Parametric polymorphism, also known as generics, is a programming language feature with implications for compiler design. The word polymorphism in general means that a value or other entity that can have more than one type. We have already talked about subtype polymorphism, in which a value of one type can act like another (super)type. Subtyping places constraints on how we implemented objects. In parametric polymorphism, the ability for something to have more than one “shape” is by introducing a type parameter. A typical motivation for parametric polymorphism is to support generic collection libraries such as the Java Collection Framework. Prior to the introduction of parametric polymorphism, all that code could know about the contents of a Set or Map was that it contained Objects. This led to code that was clumsy and not type-safe. With parametric polymorphism, we can apply a parameterized type such as Map to particular types: a Map String, Point maps Strings to Points. We can also parameterize procedures (functions, methods) withh respect to types.i Using Xi-like syntax, we might write a is_member method that can look up elements in a map: contains K, V (c: Map K, V , k: K): Value { ... } Map K, V h m i h i ...h i p: Point = contains String, Point (m, "Hello") h i Although Map is sometimes called a parameterized type or a generic type , it isn’t really a type; it is a type-level function that maps a pair of types to a new type.
    [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]
  • Polymorphism
    Polymorphism A closer look at types.... Chap 8 polymorphism º comes from Greek meaning ‘many forms’ In programming: Def: A function or operator is polymorphic if it has at least two possible types. Polymorphism i) OverloaDing Def: An overloaDeD function name or operator is one that has at least two Definitions, all of Different types. Example: In Java the ‘+’ operator is overloaDeD. String s = “abc” + “def”; +: String * String ® String int i = 3 + 5; +: int * int ® int Polymorphism Example: Java allows user DefineD polymorphism with overloaDeD function names. bool f (char a, char b) { return a == b; f : char * char ® bool } bool f (int a, int b) { f : int * int ® bool return a == b; } Note: ML Does not allow function overloaDing Polymorphism ii) Parameter Coercion Def: An implicit type conversion is calleD a coercion. Coercions usually exploit the type-subtype relationship because a wiDening type conversion from subtype to supertype is always DeemeD safe ® a compiler can insert these automatically ® type coercions. Example: type coercion in Java Double x; x = 2; the value 2 is coerceD from int to Double by the compiler Polymorphism Parameter coercion is an implicit type conversion on parameters. Parameter coercion makes writing programs easier – one function can be applieD to many subtypes. Example: Java voiD f (Double a) { ... } int Ì double float Ì double short Ì double all legal types that can be passeD to function ‘f’. byte Ì double char Ì double Note: ML Does not perform type coercion (ML has no notion of subtype). Polymorphism iii) Parametric Polymorphism Def: A function exhibits parametric polymorphism if it has a type that contains one or more type variables.
    [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]
  • 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]