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

Similar documents
Conformance. Object-Oriented Programming Spring 2015

Java Object Oriented Design. CSC207 Fall 2014

Chapter 5 Object-Oriented Programming

Data Abstraction. Hwansoo Han

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

Object-oriented Programming. Object-oriented Programming

Programming II (CS300)

Inheritance and object compatibility

Programming Language Concepts Object-Oriented Programming. Janyl Jumadinova 28 February, 2017

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

CS-202 Introduction to Object Oriented Programming

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

G Programming Languages - Fall 2012

C++ Inheritance and Encapsulation

C++ Inheritance and Encapsulation

Overriding המחלקה למדעי המחשב עזאם מרעי אוניברסיטת בן-גוריון

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

Programming II (CS300)

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

CH. 2 OBJECT-ORIENTED PROGRAMMING

What is Inheritance?

What are the characteristics of Object Oriented programming language?

Inheritance -- Introduction

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

UNIT 3 ARRAYS, RECURSION, AND COMPLEXITY CHAPTER 11 CLASSES CONTINUED

OBJECT ORIENTED PROGRAMMING USING C++

Inheritance, and Polymorphism.

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

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

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

ECE 3574: Dynamic Polymorphism using Inheritance

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

Exercise 3 Subtyping and Behavioral Subtyping October 13, 2017

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U

Strict Inheritance. Object-Oriented Programming Winter

Inclusion Polymorphism

Object Oriented Issues in VDM++

Data Structures and Other Objects Using C++

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Object Oriented Programming. Java-Lecture 11 Polymorphism

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

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

Lecture 4: Extending Classes. Concept

Inheritance and Polymorphism

OVERRIDING. 7/11/2015 Budditha Hettige 82

Information System Design (IT60105)

Subtypes and Subclasses

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Classes and Inheritance Extending Classes, Chapter 5.2

Introduction to Object-Oriented Programming

1 Shyam sir JAVA Notes

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Objects, Subclassing, Subtyping, and Inheritance

Object-Oriented Concepts and Design Principles

Implementing Object Equivalence in Java Using the Template Method Design Pattern

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

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

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

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

Strict Inheritance. Object-Oriented Programming Spring 2008

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

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

PROGRAMMING LANGUAGE 2

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

Inheritance, Polymorphism, and Interfaces

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1

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

Practice for Chapter 11

CS260 Intro to Java & Android 03.Java Language Basics

More Relationships Between Classes

Type Hierarchy. Lecture 6: OOP, autumn 2003

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

Polymorphism Part 1 1

Chapter 6 Introduction to Defining Classes

Type Hierarchy. Comp-303 : Programming Techniques Lecture 9. Alexandre Denault Computer Science McGill University Winter 2004

CS-XXX: Graduate Programming Languages. Lecture 22 Class-Based Object-Oriented Programming. Dan Grossman 2012

Subtyping (Dynamic Polymorphism)

CSC 1214: Object-Oriented Programming

Inheritance. Transitivity

BCS THE CHARTERED INSTITUTE FOR IT. BCS HIGHER EDUCATION QUALIFICATIONS BCS Level 5 Diploma in IT OBJECT ORIENTED PROGRAMMING

C++ without Classes. CMSC433, Fall 2001 Programming Language Technology and Paradigms. More C++ without Classes. Project 1. new/delete.

Object typing and subtypes

CS558 Programming Languages Winter 2013 Lecture 8

C++ Important Questions with Answers

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

ENCAPSULATION AND POLYMORPHISM

Chapter 4 Defining Classes I

Inheritance. Unit 8. Summary. 8.1 Inheritance. 8.2 Inheritance: example. Inheritance Overriding of methods and polymorphism The class Object

VIRTUAL FUNCTIONS Chapter 10

COP 3330 Final Exam Review

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

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

Comp 249 Programming Methodology

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

C++ Programming: Polymorphism

Computational Applications in Nuclear Astrophysics using Java Java course Lecture 6

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

First IS-A Relationship: Inheritance

Transcription:

Conformance Conformance and Class Invariants Same or Better Principle Access Conformance Contract Conformance Signature Conformance Co-, Contra- and No-Variance Overloading and Overriding Inheritance as an Operator What s Conformance? Overriding: replace method body in sub-class. Polymorphism: subclass is usable wherever superclass is usable. Dynamic Biding: consequence of overriding + polymorphism. Select right method body Conformance: overriding and overridden should be equivalent Superclass f(arg1, arg2) xxx Subclass f(arg1, arg2) yyy p->f(...) p->f(...) p yyy should "conform" to xxx Conformance and Class Invariants Question: Let v be the invariant of a class C. Let v be the invariant of a class C derived from C. Then, what should be the relationship between v and v? Answer: v v Rationale: a non-overridden method of C assumes v. This assumption must hold even if the method is applied to an object of class C. More generally: we would want to require also: v v but this is impossible to achieve since v refers to new attributes. Example: A Square inheriting from Rectangle. Addition to class invariant: sides are equal. Conformance and Overriding Thanks to the dynamic binding and polymorphism combination, a client cannot tell which version of a method will be invoked. Ideally, an overriding method should be semantically compatible with the overridden one. All versions of draw should draw the object. Not well-defined. Impossible to guarantee! We must content ourselves with conformance in the following aspects: Access. Contract: pre- and post-conditions, thrown exceptions. Signature: input arguments, output arguments, input-output arguments, function result.

Same or better Principle Same or better: An overriding method should have at least the same functionality as the overridden method. Overriding should not pose surprises to client. More realistically: All that can be checked is static typing. The type of the overriding method should be a super-type of the type of the overridden one. The overriding method should have the same or more calling patterns as the overridden one. Access Conformance All versions of a method should have the same visibility. Smalltalk: All methods are public. Eiffel: Inheritance and export are orthogonal. Sub-class is not strictly a sub-type. C++: Not enforced, may lead to breaking of encapsulation. class Base virtual void f(void); class Derived: public Base private: void f(void); y, *py = &y; Base *px = py; py->f(); // Error! Derived::f is private. px->f(); // OK! (but breaks encapsulation.) Access Control Revisited Friendship and Overriding The overriding method should be visible to all components to which the overridden one is visible. A friend of base class is not necessarily a friend of the derived class. Example: Overriding enhancing visibility in C++. class Base protected: virtual void f(void); class Derived: public Base void f(void); // Visibility is increased. y, *py = &y; class Derived; class Base friend void amigo(derived *); protected: virtual void f(void); class Derived: public Base void f(void); // Visibility is the same, or is it? y, *py = &y; Base *px = py; px->f(); // Error! Base::f is protected. py->f(); // OK! Derived::f is public. amigo(derived *p) p->f(); // Error! Derived::f is private. Base *px = p; // Simple up casting. px->f(); // OK! now the same Derived::f is accessible.

Contract Conformance Rules of contract conformance. Pre-condition: Overriding method must demand the same or less from its client. Post-condition: Overriding method must promise the same or more to its client. Exceptions: Overriding method must not throw any exceptions that the overridden doesn t. Rationale: Same or better principle. Contracts and Inheritance in Eiffel: Pre and post conditions are inherited. They can be refined, but never replaced. Pre-condition refinement: old_pre_condition or new_pre_condition Post-condition refinement: old_post_condition and new_post_condition Contracts and Inheritance in C++: The exception-specification (throw list) of an overriding function must be at least as restrictive as that of the overridden function. Signature Conformance Elements of signature Input arguments Output arguments Input-Output arguments Result No-variance: The type in signature cannot be changed. Co-variance: Change of type in the signature is in the same direction as that of the inheritance. Contra-variance: Change of type in the signature is in the opposite direction as that of the inheritance. Conformance: Contra-variant input arguments. Co-variant output arguments. No-variant input-output arguments. Co-variant return value. Type of Arguments For simplicity, we consider only input arguments. Suppose that: m is a method of a base class m takes an argument of class C m is overridden by m in a derived class What is the type of the corresponding argument of m in the derived class? Variance Type No-variance Must be C Argument Type Programming Language Example C++ Covariance is Natural & Essential Contra-variance Co-variance C or base class thereof C or derived class thereof Sather Eiffel More examples: Base: Graph and Node. Derived: MyGraph and MyNode Base: Animal and Food. Derived: Cat and Bones Base: Number and Number. Derived: Integer and Integer

Internal Co-variance class Employee //.. virtual bool operator ==(const Employee &e); //... class Manager: public Employee //.. virtual bool operator ==(const Manager &m); Co-variance is Unsafe f() Employee *e1 = new Employee; Employee *e2 = new Manager; *e2 == *e1 ; // Run time error! The error occurs since Manager::operator ==() is called Formal argument is of type Manager & Actual argument is of type Employee & Hence, run time type error! Conversely, it can be easily seen that contravariance is safe, but usually unnatural! Pointer to Singly Linked List Co-variance is Unsafe Co-variance and Strong Typing We have seen that co-variance is type unsafe. It may generate run-time type errors. How can co-variance exist in Eiffel, which is supposed to be a strongly-typed language? The simple answer: Break the tie between inheritance and subtyping. If an heir overrides co-variantly, then it is no longer a sub-type of the parent. Inclusion polymorphism doesn t work any more for this heir. However, inclusion polymorphism is essential for using inherited methods! So, the tie cannot be broken so lightheadedly. The real answer: A global system survey: What are all the types which may ever be assigned to each variable. For each co-variant message sent to a specific variable, check that the co-variant conditions are satisfied if the variable assumes any of its essential types. Same process enables the orthogonality and export.

As a rule: No Variance! Variance in C++ Exact match in signature required between: Overriding method Overridden method Relaxation: Co-variance is allowed in return value Must have reference semantics (pointer or reference). Relatively new addition (1992) Absolutely type safe Quite useful Conformance and # Arguments Suppose that: m is a method of a base class taking n arguments m is overridden by m in a derived class. Then, how many arguments should m have? Exactly n: Most current programming languages. n or less: It does not matter which arguments are omitted as long as naming is consistent. n or more: The BETA programming language (daughter of Simula). Note that adding arguments in an overriding method violates the same or better principle! More generally: how should the type of m relate to that of m? Define virtual constructors Virtual constructors are an effective technique for implementing cut and shape palettes in a GUI draw application. Variance in C++ (cont.) Using the virtual constructors class Employee virtual Employee *clone(void) return new Employee(*this); class Manager: public Employee virtual Manager *clone(void) return new Manager(*this); f(void) Employee *e1 = new Employee; Employee *e2 = new Manager; Employee *e3; e3 = e1->clone (); // e3 points to an Employee e3 = e2->clone (); // e3 points to a Manager Overriding and Overloading The type of an overriding function must be a supertype of that of the overridden function. In C++: The types of both functions must be the same. (Up to the co-variance of reference return type) An overriding function in C++ cannot overload a definition in the base class. If types were not the same, then the function in the derived class would hide all functions of the same name in the base class. Example: class Array virtual int& operator[](int i); int operator[](int i) const;... class CheckedArray: public Array int& operator[](int i); // Hides Array::operator[](int i) const

High-Level Methods in the Array Class Straightforward implementation of the accessor: int Array::operator[](int i) const return buff[i]; Implementation of the accessor as a high-level method: int Array::operator[](int i) const return (*const_cast<array *const>this)[i]; // Invoke the virtual function member // operator[](int) Deprecated technique: Unhiding class CheckedArray: protected Array Array::operator[];... Future compilers technique: class CheckedArray: protected Array using Array::operator[];...