Object typing and subtypes

Similar documents
The Java Programming Language

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

Subtyping (Dynamic Polymorphism)

C++ Yanyan SHEN. slide 1

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

Objects, Encapsulation, Inheritance (2)

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

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

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

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

Some instance messages and methods

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

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

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

LaboratoriodiProgrammazione III

G Programming Languages - Fall 2012

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

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

Procedure and Object- Oriented Abstraction

Introduction to Programming Using Java (98-388)

Conformance. Object-Oriented Programming Spring 2015

Subtyping: broad definitions. Not Subtyping: type variable instantiation. Mutable Records (half like ML, half like Java/Scala)

Quiz. Programming Languages. CSE 130 : Fall Lecture 16: Static Types for Objects. Ranjit Jhala UC San Diego

Polymorphism. Miri Ben-Nissan (Kopel) Miri Kopel, Bar-Ilan University

CSE 431S Type Checking. Washington University Spring 2013

COP 3330 Final Exam Review

CS153: Compilers Lecture 11: Compiling Objects

Java Object Oriented Design. CSC207 Fall 2014

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

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

Types. Type checking. Why Do We Need Type Systems? Types and Operations. What is a type? Consensus

Francesco Nidito. Programmazione Avanzata AA 2007/08

Chapter 5 Object-Oriented Programming

Francesco Nidito. Programmazione Avanzata AA 2007/08

2. The object-oriented paradigm

CS558 Programming Languages Winter 2013 Lecture 8

S.No Question Blooms Level Course Outcome UNIT I. Programming Language Syntax and semantics

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

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

Programming Languages: OO Paradigm, Polymorhism and Class Members

Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1

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

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

What about Object-Oriented Languages?

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

CS412/CS413. Introduction to Compilers Tim Teitelbaum. Lecture 17: Types and Type-Checking 25 Feb 08

Announcements. Written Assignment 2 Due Monday at 5:00PM. Midterm next Wednesday in class, 11:00 1:00. Midterm review session next Monday in class.

CH. 2 OBJECT-ORIENTED PROGRAMMING

Data Abstraction. Hwansoo Han

CPS 506 Comparative Programming Languages. Programming Language

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

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

Object-oriented Programming. Object-oriented Programming

Type Analysis. Type Checking vs. Type Inference

An Introduction to Subtyping

Derived and abstract data types. TDT4205 Lecture 15

CS 6456 OBJCET ORIENTED PROGRAMMING IV SEMESTER/EEE

Type Hierarchy. Lecture 6: OOP, autumn 2003

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Konzepte von Programmiersprachen

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources.

Chapter 6 Introduction to Defining Classes

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

Don t Believe the Hype. CS152: Programming Languages. Lecture 21 Object-Oriented Programming. Class-based OOP. So what is OOP?

Chapter 14 Abstract Classes and Interfaces

Object Oriented Programming: Based on slides from Skrien Chapter 2

Recap. What is a type? Types in OO languages. What is a type? Types as sets. Up next, some advanced OO topics

Implementing Higher-Level Languages. Quick tour of programming language implementation techniques. From the Java level to the C level.

CSE 401/M501 Compilers

Implementing objects as in Javascript, Lua, 164 is expensive because object attributes are implemented as hashtable accesses:

CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance

Lecture #23: Conversion and Type Inference

Tokens, Expressions and Control Structures

Object Oriented Issues in VDM++

Object Oriented Paradigm

Java: introduction to object-oriented features

Conversion vs. Subtyping. Lecture #23: Conversion and Type Inference. Integer Conversions. Conversions: Implicit vs. Explicit. Object x = "Hello";

Get Unique study materials from

Object Oriented Programming. Spring 2008

CS-XXX: Graduate Programming Languages. Lecture 23 Types for OOP; Static Overloading and Multimethods. Dan Grossman 2012

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

2. The object-oriented paradigm!

What is a type? Types in OO languages. What is a type? Types as sets. Example. Clients of screensaver

Inheritance, Polymorphism and the Object Memory Model

What are the characteristics of Object Oriented programming language?

INF 212/CS 253 Type Systems. Instructors: Harry Xu Crista Lopes

Strict Inheritance. Object-Oriented Programming Spring 2008

OBJECT ORİENTATİON ENCAPSULATİON

INF 212 ANALYSIS OF PROG. LANGS Type Systems. Instructors: Crista Lopes Copyright Instructors.

Homework 6. Reading. Problems. Handout 7 CS242: Autumn November

VIRTUAL FUNCTIONS Chapter 10

CS-202 Introduction to Object Oriented Programming

VALLIAMMAI ENGINEERING COLLEGE

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

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

Chapter 13 Object Oriented Programming. Copyright 2006 The McGraw-Hill Companies, Inc.

Exercise 3 Subtyping and Behavioral Subtyping October 13, 2017

Lecture Overview. [Scott, chapter 7] [Sebesta, chapter 6]

Java Primer 1: Types, Classes and Operators

Transcription:

CS 242 2012 Object typing and subtypes Reading Chapter 10, section 10.2.3 Chapter 11, sections 11.3.2 and 11.7 Chapter 12, section 12.4 Chapter 13, section 13.3

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

Example: Smalltalk Point class class name Point super class Object class var pi instance var x y class messages and methods names and code for methods... instance messages and methods names and code for methods...

Subclass: ColorPoint class name ColorPoint super class Point class var instance var color class messages and methods newx:xv Y:yv C:cv code instance messages and methods color ^color draw code add instance variable add method override Point method

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

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 Colored_point x:y: movedx:dy: x y color draw Colored_point interface contains Point Colored_point is a subtype of Point

Implicit Object types Smalltalk/JS Each object has an interface Smalltalk: set of instance methods declared in class Example: Point { x:y:, movedx:dy:, x, y, draw} ColorPoint { x:y:, movedx:dy:, x, y, color, draw} This is a form of type Names of methods, does not include type/protocol of arguments Object expression and type Send message to object p draw p x:3 y:4 q color q movedx: 5 Dy: 2 Expression OK if message is in interface

Subtyping Relation between interfaces Suppose expression makes sense p msg:pars -- OK if msg is in interface of p Replace p by q if interface of q contains interface of p Subtyping If interface is superset, then a subtype Example: ColorPoint subtype of Point Sometimes called conformance Can extend to more detailed interfaces that include types of parameters

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

Smalltalk Collection Hierarchy Collection isempty, size, includes:, at: Indexed Updatable at:put: Set add: remove: Array Dictionary associationat: Sorted collection sortblock: replacefrom:to:with: Subtyping Inheritance

C++ Subtyping Subtyping in principle A <: B if every A object can be used without type error whenever a B object is required Example: Point: int getx(); void move(int); Public members ColorPoint: int getx(); int getcolor(); void move(int); Public members void darken(int tint); C++: A <: B if class A has public base class B

Implementation of subtyping No-op Dynamically-typed languages C++ object representations (single-inheritance only) circle *c = new Circle(p,r); shape *s = c; // s points to circle c Conversion C++ object representations w/multiple-inheritance C *pc = new C; B *pb = pc; A *pa = pc; // may point to different position in object A C B

Smalltalk/JavaScript Representation Point object Point class Template 2 3 x y Method dictionary newx:y: draw move... ColorPoint object 4 5 red ColorPoint class Template x y color Method dictionary newx:y:c: color draw This is a schematic diagram meant to illustrate the main idea. Actual implementations may differ.

C++ Run-time representation Point object Point vtable Code for move vptr x 3 ColorPoint object ColorPoint vtable Code for move vptr x c 5 blue Code for darken Data at same offset Function pointers at same offset

C++: virtual function lookup Point object Point vtable Code for move vptr x 3 ColorPoint object ColorPoint vtable Code for move vptr x c 5 blue Code for darken Point p = new Pt(3); p->move(2); // (*(p->vptr[0]))(p,2)

C++: virtual function lookup, part 2 Point object Point vtable Code for move vptr x 3 ColorPoint object ColorPoint vtable Code for move vptr x c 5 blue Code for darken Point cp = new ColorPt(5,blue); cp->move(2); // (*(cp->vptr[0]))(cp,2)

C++ Multiple Inheritance A B C C object C-as-A vtbl pa, pc pb vptr A data vptr B data C data A object B object & C::f 0 C-as-B vtbl & B::g 0 & C::f Offset in vtbl is used in call to pb->f, since C::f may refer to A data that is above the pointer pb Call to pc->g can proceed through C-as-B vtbl

Independent classes not subtypes class Point { public: int getx(); void move(int); protected:... private:... }; class ColorPoint { public: int getx(); void move(int); int getcolor(); void darken(int); protected:... }; private:... C++ does not treat ColorPoint <: Point as written Need public inheritance ColorPoint : public Point Why??

Why C++ design? Client code depends only on public interface In principle, if ColorPoint interface contains Point interface, then any client could use ColorPoint in place of point However -- offset in virtual function table may differ Lose implementation efficiency (like Smalltalk) Without link to inheritance Subtyping leads to loss of implementation efficiency Also encapsulation issue: Subtyping based on inheritance is preserved under modifications to base class

Recurring subtype issue: downcast The Simula type of an object is its class Simula downcasts are checked at run-time Example: class A( );... A class B( );... ref (A) a :- new A( ) ref (B) b :- new B( ) a := b /* OK since B is subclass of A */... b := a /* compiles, but run-time test */ up B A C down

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 If A <: B, then C A <: C B Subtyping for function arguments 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)

Examples If circle <: shape, then circle shape circle circle shape shape shape circle C++ compilers recognize limited forms of function subtyping

Subtyping with functions class Point { public: int getx(); virtual Point *move(int); protected:... private:... }; class ColorPoint: public Point { public: Inherited, but repeated int getx(); here for clarity int getcolor(); ColorPoint * move(int); void darken(int); protected:... private:... }; In principle: ColorPoint <: Point In practice: This is covariant case; contravariance is another story

Subtyping principles (recap) Width subtyping for object types i > j [m 1 : 1,, m i : i ] <: [m 1 : 1,, m j : j ] Depth subtyping for object types i j i <: i [m 1 : 1,, m i : J ] <: [m 1 : 1,, m j : j ] Function subtyping <: <: <:

Subtyping recursive types Principle s <:t (s) <: (t) type s = (s) <: type t = (t) s not in (t) t not in (s) Example cp <: p { mv: int cp} <: { mv: int p } type cp = { mv: int cp} <: type p = { mv: int p}

Java Types Two general kinds of types Primitive types not objects Integers, Booleans, etc Reference types Classes, interfaces, arrays No syntax distinguishing Object * from Object Static type checking Every expression has type, determined from its parts Some auto conversions, many casts are checked at run time Example, assuming A <: B If A x, then can use x as argument to method that requires B If B x, then can try to cast x to A Downcast checked at run-time, may raise exception

Classification of Java types Reference Types Object Object[ ] Throwable Shape Shape[ ] Circle Square Circle[ ] Square[ ] Exception types user-defined arrays Primitive Types boolean int byte float long

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

Java class subtyping Signature Conformance Subclass method signatures must conform to superclass Three ways signature could vary Argument types Return type Exceptions How much conformance is needed in principle? Java rule Java 1.1: Arguments and returns must have identical types, may remove exceptions Java 1.5: covariant return type specialization

Interface subtyping: example interface Shape { public float center(); public void rotate(float degrees); } interface Drawable { public void setcolor(color c); public void draw(); } class Circle implements Shape, Drawable { // does not inherit any implementation // but must define Shape, Drawable methods } Q: can interfaces be recursive?

Properties of interfaces Flexibility Allows subtype graph instead of tree Avoids problems with multiple inheritance of implementations (remember C++ diamond ) Cost Offset in method lookup table not known at compile Different bytecodes for method lookup one when class is known one when only interface is known search for location of method cache for use next time this call is made (from this line) More about this later

Array types Automatically defined Array type T[ ] exists for each class, interface type T Cannot extend array types (array types are final) Multi-dimensional arrays are arrays of arrays: T[ ] [ ] Treated as reference type An array variable is a pointer to an array, can be null Example: Circle[] x = new Circle[array_size] Anonymous array expression: new int[] {1,2,3,... 10} Every array type is a subtype of Object[ ], Object Length of array is not part of its static type

Array subtyping Covariance if S <: T then S[ ] <: T[ ] Standard type error class A { } class B extends A { } B[ ] barray = new B[10] A[ ] aarray = barray // considered OK since B[] <: A[] aarray[0] = new A() // compiles, but run-time error // raises ArrayStoreException

Covariance problem again Simula problem If A <: B, then A ref <: B ref Needed run-time test to prevent bad assignment Covariance for assignable cells is not right in principle Explanation interface of T reference cell is put : T T ref get : T ref T Remember covariance/contravariance of functions

Afterthought on Java arrays Date: Fri, 09 Oct 1998 09:41:05-0600 From: bill joy Subject: [discussion about java genericity] actually, java array covariance was done for less noble reasons : it made some generic "bcopy" (memory copy) and like operations much easier to write... I proposed to take this out in 95, but it was too late (...). i think it is unfortunate that it wasn't taken out... it would have made adding genericity later much cleaner, and [array covariance] doesn't pay for its complexity today. wnj

Java Exceptions Similar basic functionality to other languages Constructs to throw and catch exceptions Dynamic scoping of handler Some differences An exception is an object from an exception class Subtyping between exception classes Use subtyping to match type of exception or pass it on Similar functionality to ML pattern matching in handler Type of method includes exceptions it can throw Actually, only subclasses of Exception (see next slide)

Exception Classes Throwable checked exceptions Exception Runtime Exception Error User-defined exception classes Unchecked exceptions If a method may throw a checked exception, then exception must be in the type of the method

Why define new exception types? Exception may contain data Class Throwable includes a string field so that cause of exception can be described Pass other data by declaring additional fields or methods Subtype hierarchy used to catch exceptions catch <exception-type> <identifier> { } will catch any exception from any subtype of exception-type and bind object to identifier

Subtyping concepts Type of an object represents its interface Subtyping has associated substitution principle If A <: B, then A objects can be used in place of B objects Implicit subtyping in dynamically typed lang Relation between interfaces determines substitutivity Explicit subtyping in statically typed languages Type checker may recognize some subtyping Issues: programming style, implementation efficiency Covariance and contravariance Function argument types reverse order Problems with Java array covariance

Principles Object width subtyping Function covariance, contravariance Object type depth subtyping Subtyping recursive types

Applications of principles Dynamically typed languages If A <: B in principle, then can use A objects in place of B objects C++ Class subtyping only when public base class Compiler allows width subtyping, covariant depth subtyping. (Think about why ) Java Class subtyping only when declared using extends Class and interface subtyping when declared Compiler allows width subtyping, covariant depth subtyping Additional typing issues related to generics