Subtyping (Dynamic Polymorphism)

Similar documents
C++ Yanyan SHEN. slide 1

Object typing and subtypes

History C++ Design Goals. How successful? Significant constraints. Overview of C++

Objects, Encapsulation, Inheritance (2)

Objects. Deian Stefan (Adopted from my & Edward Yang s CS242 slides)

Outline. Central concepts in OO languages Objects as activation records (Simula) Dynamically-typed object-oriented languages

Simula 67. Simula and Smalltalk. Comparison to Algol 60. Brief history. Example: Circles and lines. Objects in Simula

Week 7. Statically-typed OO languages: C++ Closer look at subtyping

Simula and Smalltalk. Comparison to Algol 60. Brief history. Example: Circles and lines. Objects in Simula. John Mitchell

Lecture 13: Object orientation. Object oriented programming. Introduction. Object oriented programming. OO and ADT:s. Introduction

Some instance messages and methods

Design issues for objectoriented. languages. Objects-only "pure" language vs mixed. Are subclasses subtypes of the superclass?

The Java Programming Language

CPS 506 Comparative Programming Languages. Programming Language

CS558 Programming Languages Winter 2013 Lecture 8

References: Chapters 10 and 11 Chapters 8, and 12( 2 and 3)

Thanks! Review. Course Goals. General Themes in this Course. There are many programming languages. Teaching Assistants. John Mitchell.

Data Abstraction. Hwansoo Han

Object Oriented Paradigm

Object-Oriented Languages and Object-Oriented Design. Ghezzi&Jazayeri: OO Languages 1

Object-oriented Programming. Object-oriented Programming

M301: Software Systems & their Development. Unit 4: Inheritance, Composition and Polymorphism

Lecture 15: Object-Oriented Programming

CS558 Programming Languages

Java Object Oriented Design. CSC207 Fall 2014

Object Oriented Issues in VDM++

G Programming Languages - Fall 2012

Chapter 5 Object-Oriented Programming

G Programming Languages Spring 2010 Lecture 9. Robert Grimm, New York University

Lecture Notes on Programming Languages

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

What about Object-Oriented Languages?

Procedure and Object- Oriented Abstraction

Lecture 23: Object Lifetime and Garbage Collection

C++ Important Questions with Answers

C++ Part 2 <: <: C++ Run-Time Representation. Smalltalk vs. C++ Dynamic Dispatch. Smalltalk vs. C++ Dynamic Dispatch

Comp 311 Principles of Programming Languages Lecture 21 Semantics of OO Languages. Corky Cartwright Mathias Ricken October 20, 2010

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Lecturer: William W.Y. Hsu. Programming Languages

CSE 401/M501 Compilers

Advanced oo concepts Specialization of behaviour? Multiple inheritance - alternatives to. Inner classes Classes

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE

Method Resolution Approaches. Dynamic Dispatch

Practice for Chapter 11

COSC252: Programming Languages: Abstraction and OOP. Jeremy Bolton, PhD Asst Teaching Professor. Copyright 2015 Pearson. All rights reserved.

Chapter 10 :: Data Abstraction and Object Orientation

Advanced Database Applications. Object Oriented Database Management Chapter 13 10/29/2016. Object DBMSs

CSE 504. Expression evaluation. Expression Evaluation, Runtime Environments. One possible semantics: Problem:

Chapter 9 :: Data Abstraction and Object Orientation

Types and Classes. I II From predefined (simple) and user-defined (composite) types via Abstract data types

COMP322 - Introduction to C++

CS250 Final Review Questions

Inheritance, and Polymorphism.

What are the characteristics of Object Oriented programming language?

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

Today s lecture. CS 314 fall 01 C++ 1, page 1

CS152: Programming Languages. Lecture 23 Advanced Concepts in Object-Oriented Programming. Dan Grossman Spring 2011

Intro to OOP Visibility/protection levels and constructors Friend, convert constructor, destructor Operator overloading a<=b a.

Chapter 11. Categories of languages that support OOP: 1. OOP support is added to an existing language

Chapter 5: Procedural abstraction. Function procedures. Function procedures. Proper procedures and function procedures

CSE 452: Programming Languages. Previous Lecture. From ADTs to OOP. Data Abstraction and Object-Orientation

C++ Programming: Polymorphism

COMP322 - Introduction to C++ Lecture 09 - Inheritance continued

Inheritance, Polymorphism and the Object Memory Model

OOPLs - Inheritance. Inheritance

Inheritance and Substitution (Budd chapter 8, 10)

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II

Object Oriented Programming

Topics. Modularity and Object-Oriented Programming. Dijkstra s Example (1969) Stepwise Refinement. Modular program development

PROGRAMMING LANGUAGE 2

Administrivia. CMSC433, Fall 2001 Programming Language Technology and Paradigms. Administrivia (cont.) Project 1. Copy constructor.

CSE 307: Principles of Programming Languages

CLASSES AND OBJECTS IN JAVA

CS250 Final Review Questions

Interfaces, Mixins, & Multiple Inheritance

Concepts of Programming Languages

Chapter 6 Introduction to Defining Classes

What is Inheritance?

CSE Lecture 3: Objects 2 September Nate Nystrom University of Texas at Arlington

STRUCTURING OF PROGRAM

Konzepte von Programmiersprachen

What s Conformance? Conformance. Conformance and Class Invariants Question: Conformance and Overriding

Exceptions and Continuations. Lecture #19: More Special Effects Exceptions and OOP. Approach II: Non-Standard Return. Approach I: Do Nothing

Class, Variable, Constructor, Object, Method Questions

Compiler Construction Lent Term 2015 Lectures 10, 11 (of 16)

Written by John Bell for CS 342, Spring 2018

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Data Structures (list, dictionary, tuples, sets, strings)

Chapter 10 Object-Oriented Programming

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Programming Languages: OO Paradigm, Polymorhism and Class Members

Object Oriented Languages. Hwansoo Han

DATA TYPES. CS 403: Types and Classes DATA TYPES (CONT D)

Conformance. Object-Oriented Programming Spring 2015

Lecture 16: Object Programming Languages

Overview. Elements of Programming Languages. Objects. Self-Reference

Inheritance -- Introduction

CS-202 Introduction to Object Oriented Programming

Transcription:

Fall 2018 Subtyping (Dynamic Polymorphism) Yu Zhang Course web site: http://staff.ustc.edu.cn/~yuzhang/tpl

References PFPL - Chapter 24 Structural Subtyping - Chapter 27 Inheritance TAPL (pdf) - Chapter 15 Subtyping [Concepts in PLs]

Subtyping and Inheritance Interface - The external view of an object Subtyping - Relation between interfaces Implementation - The internal representation of an object Inheritance - Relation between implementations

Various Object-Oriented Languages Pure dynamically-typed OO languages - Object implementation and run-time lookup - Class-based languages (Smalltalk) - Prototype-based languages (Self, JavaScript) Statically-typed OO languages - C++ using static typing to eliminate search problems with C++ multiple inheritance - Java using Interfaces to avoid multiple inheritance

Smalltalk Developed at Xerox PARC: Smalltalk-76, -80 Object metaphor extended and refined - Used some ideas from Simula, but very different lang - Everything is an object, even a class - All operations are messages to objects Terminology Object Instance of some class Class Defines behavior of its object Selector Name of a message Message Selector together with parameter values Method Subclass Code used by a class to respond to message Instance variable Data stored in object Class defined by giving incremental modifications to some superclass

Point class Smalltalk: Example ColorPoint class add instance variable class name super class class var Point Object pi instance var x y class messages and methods < names and code for 3 methods, i.e. newx:y:, neworigin, initialize> instance messages and methods < names and code for 5 methods i.e. x:y:, movedx:dy:, x, y, draw> class name super class class var ColorPoint Point instance var color class messages and methods newx:xv Y:yv C:cv < code > instance messages and methods color < code > draw < code > override override add method

Smalltalk: Run-time Representation This is a schematic diagram meant to illustrate the main idea. Actual implementations may differ.

Smalltalk Summary Class - creates objects that share methods - pointers to template, dictionary, parent class Objects: created by a class, contains instance variables Encapsulation - methods public, instance variables hidden Subtyping: implicit, no static type system Inheritance: subclasses, self, super Single inheritance in Smalltalk-76, Smalltalk-80

Smalltalk: Object Interfaces Interface - The messages understood by an object Example: point x:y: set x,y coordinates of point movedx:dy: method for changing location x returns x-coordinate of a point y returns y-coordinate of a point draw display point in x,y location on screen The interface of an object is its type

Smalltalk: Subtyping If interface A contains all of interface B, then A objects can also be used B objects. Point x:y: movedx:dy: x y draw ColorPoint x:y: movedx:dy: x y color draw ColorPoint interface contains Point ColorPoint is a subtype of Point

Subtyping and Inheritance Smalltalk/JavaScript subtyping is implicit - Not a part of the programming language - Important aspect of how systems are built Inheritance is explicit - Used to implement systems - No forced relationship to subtyping

C++ C++ is an object-oriented extension of C, Bell Labs Object-oriented features - Classes - Objects, with dynamic lookup of virtual functions - Inheritance Single and multiple inheritance Public and private base classes - Subtyping Tied to inheritance mechanism - Encapsulation Public, private, protected visibility

C++: Virtual functions Member functions are either - Virtual, if explicitly declared or inherited as virtual - Non-virtual otherwise Virtual functions - Accessed by indirection through ptr in object - May be redefined in derived (sub) classes Non-virtual functions - Are called in the usual way. Just ordinary functions. - Cannot redefine in derived classes (except overloading) Pay overhead only if you use virtual functions

Run-time Representation

Compare to Smalltalk/JavaScript This is a schematic diagram meant to illustrate the main idea. Actual implementations may differ.

Multiple Inheritance Name clashes class A { public: virtual void f() { } }; class B { public: virtual void f() { } }; class C : public A, public B{ }; C* p; p->f(); // error Implicit resolution - Language resolves name conflicts with arbitrary rule Explicit resolution (C++) - Programmer must explicitly resolve name conflicts Disallow name clashes - Programs are not allowed to contain name clashes No solution is always best

Multiple Inheritance Name clashes class A { public: virtual void f() { } }; class B { public: virtual void f() { } }; class C : public A, public B{ }; C* p; p->f(); // error Rewrite class C to call A::f explicitly => eliminate ambiguity class C : public A, public B{ public: void virtual f() { A::f(); }

vtable for Multiple Inheritance class A { public: virtual void f(); }; class B { public: int y; virtual void g(); virtual void f(); }; class C : public A, public B{ public: int z; virtual void f(); }; C *pc = new C; B *pb = pc; A * pa=pc; pa, pb, pc point to same object, but different static types.

Diamond Inheritance in C++ Standard base classes - D members appear twice in C Virtual base classes class A : public virtual D { } - Avoid duplication of base class members - Require additional pointers so that D part of A, B parts of object can be shared C++ multiple inheritance is complicated in because of desire to maintain efficient lookup

C++ Subtyping Subtyping in principle - A <: B if every A object can be used without type error whenever a B object is required C++: A <: B if class A has public base class B - Independent classes not subtypes

Function Subtyping Subtyping principle - A <: B if an A expression can be safely used in any context where a B expression is required Subtyping for function results (Covariance) - If A <: B, then C A <: C B Subtyping for function arguments (Contravariance) - If A <: B, then B C <: A C Terminology - Covariance( 协变 ): A <: B implies F(A) <: F(B) - Contravariance( 逆变 ): A <: B implies F(B) <: F(A)

Subtyping Principles Products - Width subtyping( 一个较宽的元组类型是一个较窄的元组类型 的子类型 ) i j [ m :,, m : ] : [ m :,, m : ] 1 1 i i 1 1 j j - Depth subtyping (Covariance) 1 1 j j 1 1 j j - Function subtyping i : [ m :,, m : ] : [ m :,, m : ] : : : i

Java 1990-95 James Gosling and others at Sun Syntax similar to C++ Object - has fields and methods - is allocated on heap, not run-time stack - accessible through reference (only ptr assignment) - garbage collected Dynamic lookup - Similar in behavior to other languages - Static typing => more efficient than Smalltalk - Dynamic linking, interfaces => slower than C++

Inheritance Similar to Smalltalk, C++ Subclass inherits from superclass - Single inheritance only (but Java has interfaces) Some additional features - Conventions regarding super in constructor and finalize methods - Final classes and methods cannot be redefined

Interfaces vs Multiple Inheritance C++ multiple inheritance - A single class may inherit from two base classes - Constraints of C++ require derived class representation to resemble all base classes Java interfaces - A single class may implement two interfaces - No inheritance (of implementation) involved - Java implementation (discussed later) does not require similarity between class representations

Subtyping Primitive types - Conversions: int -> long, double -> long, Class subtyping similar to C++ - Subclass produces subtype - Single inheritance => subclasses form tree Interfaces - Completely abstract classes no implementation - Multiple subtyping Arrays Interface can have multiple subtypes (implements, extends) - Covariant subtyping not consistent with semantic principles