Subtype Polymorphism, Subtyping vs. Subclassing, Liskov Substitution Principle.

Slides:



Advertisements
Similar presentations
Overriding CMPS Overriding Recall, a method in a child class overrides a method in the parent class, if it has the same name and type signature.
Advertisements

Identity and Equality Based on material by Michael Ernst, University of Washington.
SUMMARY: abstract classes and interfaces 1 Make a class abstract so instances of it cannot be created. Make a method abstract so it must be overridden.
Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
C12, Polymorphism “many forms” (greek: poly = many, morphos = form)
5/17/2015 OO Design: Liskov Substitution Principle 1.
AbstractClassesInterfacesPolymorphism1 Abstract Classes, Interfaces, Polymorphism Barb Ericson Georgia Tech April 2010.
Georgia Institute of Technology Workshop for CS-AP Teachers Chapter 3 Advanced Object-Oriented Concepts.
C8: Understanding Inheritance. Intuitive description Intuitive: FLORISTS are SHOPKEEPERS, inheriting various shopkeeper behaviors Tension in OOP languages:
Inheritance and object compatibility Object type compatibility An instance of a subclass can be used instead of an instance of the superclass, but not.
CSE341: Programming Languages Lecture 26 Subtyping for OOP Dan Grossman Fall 2011.
CSE115: Introduction to Computer Science I Dr. Carl Alphonce 219 Bell Hall Office hours: M-F 11:00-11:
Overview of Java (continue). Announcements You should have access to your repositories and HW0 If you have problems getting HW0, let me know If you’ve.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
Inheritance (notes for 10/26 lecture). Inheritance Inheritance is the last of the relationships we will study this semester. Inheritance is (syntactically)
Polymorphism. Lecture Objectives To understand the concept of polymorphism To understand the concept of static or early binding To understand the concept.
Subclasses and Subtypes CMPS Subclasses and Subtypes A class is a subclass if it has been built using inheritance. ▫ It says nothing about the meaning.
Procedure specifications CSE 331. Outline Satisfying a specification; substitutability Stronger and weaker specifications - Comparing by hand - Comparing.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
Sadegh Aliakbary Sharif University of Technology Fall 2011.
1 Abstraction  Identify important aspects and ignore the details  Permeates software development programming languages are abstractions built on hardware.
Polymorphism, Inheritance Pt. 1 COMP 401, Fall 2014 Lecture 7 9/9/2014.
Chapter 9 Object-Oriented Software Development F Software Development Process F Analyze Relationships Among Objects F Class Development F Class Design.
Class Design III: Advanced Inheritance Additional References “Object-Oriented Software Development Using Java”, Xiaoping Jia, Addison Wesley, 2002 “Core.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
Object-Oriented Design CSC 212. Announcements This course is speeding up and we are starting new material. Please see me if you feel this is going too.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
OO as a language for acm l OO phrase l Mental model of key concepts.
Types in programming languages1 What are types, and why do we need them?
CS2110: SW Development Methods Inheritance in OO and in Java Part 2: Topics: Forms of inheritance Interfaces in Java.
Type Abstraction SWE Spring October 05Kaushik, Ammann Substitution Principle “In any client code, if supertype object is substituted.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Object Oriented Programming
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Subtype Polymorphism, Subtyping vs
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Parametric Polymorphism and Java Generics. Announcements One day extension on HW5 Because of an error in my HW5 config HW6 out, due November 10 Grades.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
Subtype Polymorphism, cont. Parametric Polymorphism and Java Generics.
Evaluating an Object-Oriented Design ©SoftMoore ConsultingSlide 1.
Inheritance Type/Subtype Relationship. Inheritance Idea: An object B of one type, termed child class, inherits from another object A of another type,
CSCI-383 Object-Oriented Programming & Design Lecture 24.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
CSSE501 Object-Oriented Development. Chapter 10: Subclasses and Subtypes  In this chapter we will explore the relationships between the two concepts.
1 / 71 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 4 Programming Fundamentals using Java 1.
Interfaces, Abstract Classes, and Polymorphism. What Is an Interface? An interface is the set of public methods in a class Java provides the syntax for.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 3 – Extending classes.
DBC NOTES. Design By Contract l A contract carries mutual obligations and benefits. l The client should only call a routine when the routine’s pre-condition.
Class Relationships Lecture Oo08 Polymorphism. References n Booch, et al, The Unified Modeling Language User Guide, Chapt 10 p.125 n Fowler & Scott, UML.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
CSCI-383 Object-Oriented Programming & Design Lecture 17.
Zach Tatlock / Winter 2016 CSE 331 Software Design and Implementation Lecture 12 Subtypes and Subclasses.
Polymorphism and access control. RHS – SOC 2 What is polymorphism? In general: the ability of some concept to take on different forms In Java: the ability.
CSE 331 Subtyping slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia
Type Abstraction SWE Spring 2009.
Subtype Polymorphism, Subtyping vs
CSE 331 Software Design and Implementation
Testing, cont., Equality and Identity
Subtype Polymorphism, Subtyping vs
CSE 331 Software Design & Implementation
Software Design Lecture : 12.
CSE 331 Software Design & Implementation
Lecture 13: Subtyping Rules Killer Bear Climber
Type Abstraction SWE Spring 2013.
Liskov Substitution Principle (LSP)
Presentation transcript:

Subtype Polymorphism, Subtyping vs. Subclassing, Liskov Substitution Principle

Outline Subtype polymorphism Subtyping vs. subclassing Liskov Substitution Principle (LSP) Function subtyping Java subtyping Composition: an alternative to inheritance 2

3 Subtype Polymorphism Subtype polymorphism – the ability to use a subclass where a superclass is expected Thus, dynamic method binding class A { void m() { … } } class B extends A { void m() { … } } class C extends A { void m() { … } } Client: A a; … a.m(); // Call a.m() can bind to any of A.m, B.m or C.m at runtime! Subtype polymorphism is the essential feature of object-oriented languages Java subtype: B extends A or B implements I A Java subtype is not necessarily a true subtype! override A.m

Benefits of Subtype Polymorphism Example: Application draws shapes on screen Possible solution in C: enum ShapeType { circle, square }; struct Shape { ShapeType t }; struct Circle { ShapeType t; double radius; Point center; }; struct Square { ShapeType t; double side; Point topleft; }; 4

Benefits of Subtype Polymorphism Fall 15 CSCI 2600, A Milanova 5 void DrawAll(struct Shape *list[], int n) { int i; for (i=0; i< n; i++) { struct Shape *s = list[i]; switch (s->t) { case square: DrawSquare(s); break; case circle: DrawCircle(s); break; } What’s really bad about this solution?

Benefits of Subtype Polymorphism Fall 15 CSCI 2600, A Milanova 6 Example: OO Solution in Java: abstract class Shape { public void draw(); } class Circle extends Shape { … draw() } class Square extends Shape { … draw() } class Triangle extends Shape { … draw() } void DrawAll(Shape[] list) { for (int i=0; i < list.length; i++) { Shape s = list[i]; s.draw(); } }

Benefits of Subtype Polymorphism Fall 15 CSCI 2600, A Milanova 7 Enables extensibility and reuse In our example, we can extend Shape hierarchy with no modification to the client of hierarchy, DrawAll Thus, we can reuse Shape and DrawAll Subtype polymorphism enables the Open/closed principle Software entities (classes, modules) should be open for extension but closed for modification Credited to Bertrand Meyer

Benefits of Subtype Polymorphism Fall 15 CSCI 2600, A Milanova 8 “Science” of software design teaches Design Patterns Design patterns promote design for extensibility and reuse Nearly all design patterns make use of subtype polymorphism

What is True Subtyping? Subtyping, conceptually B is subtype of A means every B is an A In other words, a B object can be substituted where an A object is expected The notion of true subtyping connects subtyping in the real world with Java subtyping Fall 15 CSCI 2600, A Milanova 9

Examples of Subtypes Subset subtypes int is a subtype of real range [0..10] is a subtype of range [-10…10] Other subtypes Every book is a library item Every DVD is a library item Every triangle is a shape Etc. Fall 15 CSCI 2600, A Milanova 10 Item Book DVD Shape Triangle Rhombus

Subtypes are Substitutable Subtypes are substitutable for supertypes Instances of subtypes won’t surprise client by requiring “more” than the supertype Instances of subtypes won’t surprise client by returning “less” than its supertype Java subtyping is realized through subclassing Java subtype is not the same as true subtype! 11

Subtyping and Subclassing Subtyping and substitutability --- specification notions B is a subtype of A if and only if a B object can be substituted where an A object is expected, in any context Subclassing and inheritance --- implementation notions B extends A, or B implements A B is a Java subtype of A, but not necessarily a true subtype of A! 12

True Subtype We say that (class) B is a true subtype of A if B has a stronger specification than A Heed when designing inheritance hierarchies! Java subtypes that are not true subtypes are confusing and dangerous Fall 15 CSCI 2600, A Milanova 13

Subclassing. Inheritance Makes it Easy to Add Functionality class Product { private String title; private String description; private float price; public float getPrice() { return price; } public float getTax() { return getPrice()*0.08f; } … and we need a class for Products that are on sale Fall 15 CSCI 2600, A Milanova (slide due to Michael Ernst) 14

Code cloning is a bad idea! Why? class SaleProduct { private String title; private String description; private float price; private float factor; // extends Product public float getPrice() { return price*factor; } // extends Product public float getTax() { return getPrice()*0.08f; } Fall 15 CSCI 2600, A Milanova (based on an example by Michael Ernst) 15

Subclassing What’s a better way to add this functionality? Fall 15 CSCI 2600, A Milanova (based on slide by Michael Ernst) 16 class SaleProduct extends Product { private float factor; public float getPrice() { return super.getPrice()*factor; } … Subclassing keeps small extensions small

Benefits of Subclassing Don’t repeat unchanged fields and methods Simpler maintenance: fix bugs once Differences are clear (not buried under mass of similarity!) Modularity: can ignore private fields and methods of superclass Can substitute new implementations where old one is expected (the benefit of subtype polymorphism) Another example: Timestamp extends Date Fall 15 CSCI 2600, A Milanova (based on slide by Michael Ernst) 17

Subclassing Can Be Misused Poor planning leads to muddled inheritance hierarchies. Requires careful planning If a class is not a true subtype of its superclass, it can surprise clients If a class depends on implementation details of its superclass, changes in the superclass can break the subclass i.e., the “fragile base class problem” Fall 15 CSCI 2600, A Milanova (based on a slide by Michael Ernst) 18

Classic Example of Subtyping vs. Subclassing: Every Square is a Rectangle, right? Thus, class Square extends Rectangle { … } But is a Square a true subtype of Rectangle ? In other words, is Square substitutable for Rectangle in client code? class Rectangle { // effects: this post.width=w,this post.height=h public void setSize(int w, int h); // returns: area of rectangle public int area(); } Fall 15 CSCI 2600, A Milanova 19

Every Square is a Rectangle, right? class Square extends Rectangle { // requires: w = h // effects: this post.width=w,this post.height=h Choice 1: public void setSize(int w, int h); // effects: this post.width=w,this post.height=w Choice 2: public void setSize(int w, int h); // effects: this post.width=s,this post.height=s Choice 3: public void setSize(int s); // effects: this post.width=w,this post.height=h // throws: BadSizeException if w != h Choice 4: public void setSize(int w, int h); } 20

Every Square is a Rectangle, right? Choice 1 is not good It requires more! Clients of Rectangle are justified to have Rectangle r; … r.setSize(5,4) In formal terms: spec of Square’s setSize is not stronger than spec of Rectangle’s setSize Because the precondition of Rectangle’s setSize does not imply precondition of Square’s setSize Thus, a Square can’t be substituted for a Rectangle Fall 15 CSCI 2600, A Milanova 21

Every Square is a Rectangle, right? Choice 2? Client: Rectangle r; … r.setSize(5,4); assert(r.area()==20) Again, Square surprises clients with behavior that is different from Rectangle Choice 3? Clients of Rectangle can write … r.setSize(5,4). Square works with r.setSize(5) Choice 4? Throws an exception that clients of Rectangle are not expecting and therefore likely not handling Thus, a Square can’t be substituted for a Rectangle 22

Every Square is a Rectangle, right? Square is not a true subtype of Rectangle Rectangles are expected to have height and width values that can change independently Squares violate that expectation. Surprise clients Is Rectangle a true subtype of Square? No. Squares are expected to have equal height and width. Rectangles violate this expectation One solution: make them unrelated Fall 15 CSCI 2600, A Milanova 23 Shape Square Rectangle

Box is a BallContainer? class BallContainer { // modifies: this // effects: adds b to this container if b is not // already in // returns: true if b is added, false otherwise public boolean add(Ball b); … } class Box extends BallContainer { // good idea? // modifies: this // effects: adds b to this Box if b is not // already in and this Box is not full // returns: true if b is added, false otherwise public boolean add(Ball b); … } 24

Liskov Substitution Principle (LSP) – Barbara Liskov LSP: A subclass should be substitutable for its superclass, i.e., every subclass should be a true subtype of its superclass Ensure that B is a true subtype of A by reasoning at the specification level B should not remove methods from A For each B.x() that “substitutes” for A.x(), B.x()’s spec is stronger than A.x()’s spec Client: A a; … a.x(q,r); Calling a.x() can bind to B’s x(), and B’s x() should not surprise the client! 25 Turing Award, 2008

Exercise: Reason About Specs class Rectangle { // effects: this post.width=w,this post.height=h public void setSize(int w, int h); } class Square extends Rectangle { … // requires: w = h // effects: this post.width=w,this post.height=h public void setSize(int w, int h); } Fall 15 CSCI 2600, A Milanova (based on a slide by Mike Ernst) 26

Summary So Far Java subtypes (implemented using extends, implements) must be true subtypes Java subtypes that are not true subtypes are dangerous and confusing When B is a Java subtype of A, ensure B does not remove methods from A A substituting method B.x() has stronger spec than method A.x() for which it substitutes Guarantees substitutability 27

Intuition: Type Signature is a Specification Type signature (parameter types + return type) is a contract, too E.g., double f(String s, int i) {…} Precondition: arguments are a String and an int Postcondition: result is a double We need reasoning about behavior and effects, so we added requires, effects, etc. Fall 15 CSCI 2600, A Milanova 28

Function Subtyping In programming languages, function subtyping deals with the substitutability of functions Question: under what conditions on the parameter and return types A,B,C and D, is function A f(B) substitutable for C f’(D) Reasons at the level of the type signature Rule: A f(B) is a function subtype of C f’(D) iff A is a subtype of C and B is a supertype of D Guarantees substitutability! Fall 15 CSCI 2600, A Milanova 29

Type Signature of Substituting Method is Stronger Method parameters (inputs): Parameter types of A.x() may be replaced by supertypes in subclass B.x(). “contravariance” E.g., A.x(String p) and B.x(Object p) B.x() places no extra requirements on the client! E.g., client: A a; … a.x(q). Client knows to provide q as a String. Thus, client code will work fine with B.x(Object p), which asks for less, i.e., an Object, and clearly, every String is an Object Java does not allow changes in parameter types in overriding methods 30 A B

Type Signature of Substituting Method is Stronger Method returns (results): Return type of A.x() may be replaced by subtype in subclass B.x(). “covariance” E.g., Object A.x() and String B.x() B.x() does not violate expectations of the client! E.g., client: A a; … Object o = a.x(). Client expects an Object. Thus, String will work fine No new exceptions. Existing exceptions can be replaced by subtypes (i.e., subtype exceptions) Java does allow a subtype return type in an overriding method! 31 A B

Properties Class from the JDK class Hashtable { // modifies: this // effects: associates value with key public void put(Object key, Object value); // returns: value associated with key public Object get(Object key); } class Properties extends Hashtable { // simplified // modifies: this // effects: associates String value with String key public void put(String key, String value) { super.put(key, value); } // returns: value associated with key public String get(String key) { return (String) super.get(key); } 32 Properties stores String key-value pairs. It extends Hashtable so Properties is a Java subtype of Hashtable. What’s the problem?

Exercise class Hashtable { public void put(Object key, Object value); public Object get(Object key); } class Properties extends Hashtable { public void put(String key, String value); public String get(String key); } Fall 15 CSCI 2600, A Milanova (based on example by Michael Ernst) 33

Exercise class Product { Product recommend(Product p); } Which one is a function subtype of Product.recommend? class SaleProduct extends Product { Product recommend(SaleProduct p); SaleProduct recommend(Product p); Product recommend(Object p); Product recommend(Product p) throws NoSaleException; } Fall 15 CSCI 2600, A Milanova (based on example by Michael Ernst) 34

Reasoning about Specs Function subtyping reasons with type signatures Remember, type signature is a specification! Precondition: requires arguments of given type Postcondition: promises result of given type Compiler checks function subtyping Behavioral specifications add reasoning about behavior and effects Precondition: stated by requires clause Postcondition: stated by modifies, effects, returns and throws clauses To ensure B is a true subtype of A, we must reason about behavioral specifications (as we did earlier) 35

Reason about Specs Behavioral subtyping generalizes function subtyping B.x() is a true subtype (behavioral subtype) of A.x() B.x() has weaker precondition than A.x() This generalizes the requirement of function subtyping: “B.x()’s parameter is a supertype of A.x()’s parameter” Contravariance B.x() has stronger postcondition than A.x() Generalizes “B.x()’s return is a subtype of A.x()’s return” Covariance These 2 conditions guarantee B.x()’s spec is stronger than A.x()’s spec, and B.x() is substitutable for A.x()

Java Subtypes Java types are defined by classes, interfaces, primitives Java subtyping stems from declarations B extends A B implements A In a Java subtype, a “substituting” method is an overriding method Has same parameter types Has compatible (same or subtype) return type Has no additional declared exceptions 37

Overloading vs. Overriding If a method has the same name, but different parameter types, it overloads, not overrides class Hashtable { public void put(Object key, Object value); public Object get(Object key); } class Properties extends Hashtable { public void put(String key, String value); public String get(String key); } Fall 15 CSCI 2600, A Milanova 38 overload Hashtable’s put and get

Overloading vs. Overriding A method family contains multiple implementations of same name + parameter types (but not return type!) Which method family is determined at compile time based on compile-time types? E.g., family put(Object key, Object value) or family put(String key, String value) Which implementation from the method family runs, is determined at runtime based on the runtime type of the receiver 39

Remember Duration class Object { public boolean equals(Object o); } class Duration { public boolean equals(Object o); public boolean equals(Duration d); } Duration d1 = new Duration(10,5); Duration d2 = new Duration(10,5); System.out.println(d1.equals(d2)); // Compiler choses family equals(Duration d) Fall 15 CSCI 2600, A Milanova 40 Two method families.

Remember Duration class Object { public boolean equals(Object o); } class Duration { public boolean equals(Object o); public boolean equals(Duration d); } Object d1 = new Duration(10,5); Duration d2 = new Duration(10,5); System.out.println(d1.equals(d2)); // At compile-time: equals(Object o) // At runtime: Duration.equals(Object o) 41

Remember Duration class Object { public boolean equals(Object o); } class Duration { public boolean equals(Object o); public boolean equals(Duration d); } Object d1 = new Duration(10,5); Object d2 = new Duration(10,5); System.out.println(d1.equals(d2)); // Compiler choses equals(Object o) // At runtime: Duration.equals(Object o) 42

Remember Duration class Object { public boolean equals(Object o); } class Duration { public boolean equals(Object o); public boolean equals(Duration d); } Duration d1 = new Duration(10,5); Object d2 = new Duration(10,5); System.out.println(d1.equals(d2)); // Compiler choses equals(Object o) // At runtime: Duration.equals(Object o) 43

Exercise class Y extends X { … } class A { X m(Object o) { … } } class B extends A { X m(Z z) { … } } class C extends B { Y m(Z z) { … } } Fall 15 CSCI 2600, A Milanova 44 A a = new B(); Object o = new Object(); // Which m is called? X x = a.m(o); A a = new C(); Object o = new Z(); // Which m is called? X x = a.m(o);

Exercise class Y extends X { … } class W extends Z { … } class A { X m(Z z) { … } } class B extends A { X m(W w) { … } } class C extends B { Y m(W w) { … } } Fall 15 CSCI 2600, A Milanova 45 A a = new B(); W w = new W(); // Which m is called? X x = a.m(w); B b = new C(); W w = new W(); // Which m is called? X x = b.m(w);

Java Subtyping Guarantees A variable’s runtime type (i.e., the class of its runtime object) is a Java subtype of the variable’s declared class (Not true in C++!) Object o = new Date(); // OK Date d = new Object(); // Compile-time error Thus, objects always have implementations of the method specified at the call site Client: B b; … b.x() // Runtime object has x() If all subtypes are true subtypes, spec of runtime target x () is stronger than spec of B.x() 46