Polymorphism Liskov 8. Outline equals() Revisiting Liskov’s mutable vs. not rule Polymorphism Uniform methods for different types “easy” polymorphism.

Slides:



Advertisements
Similar presentations
Data Structures A data structure is a collection of data organized in some fashion that permits access to individual elements stored in the structure This.
Advertisements

Identity and Equality Based on material by Michael Ernst, University of Washington.
Cs2220: Engineering Software Class 10: Generic Datatypes Fall 2010 University of Virginia David Evans.
The Substitution Principle SWE 332 – Fall Liskov Substitution Principle In any client code, if subtype object is substituted for supertype object,
IKI 10100: Data Structures & Algorithms Ruli Manurung (acknowledgments to Denny & Ade Azurat) 1 Fasilkom UI Ruli Manurung (Fasilkom UI)IKI10100: Lecture22.
Data Abstraction II SWE 619 Software Construction Last Modified, Spring 2009 Paul Ammann.
Effective Java, Chapter 3: Methods Common to All Objects.
Searching. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an element in it static.
Searching and Sorting I 1 Searching and Sorting 1.
1 L43 Collections (3). 2 OBJECTIVES  To use the collections framework interfaces to program with collections polymorphically.  To use iterators to “walk.
Searching. Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an element in it static.
Comparing Objects in Java. The == operator When you define an object, for instance Person p = new Person("John", 23); we talk about p as if its value.
CS 106 Introduction to Computer Science I 04 / 30 / 2010 Instructor: Michael Eckmann.
Specifications Liskov Chapter 9 SWE 619 Last Updated Fall 2008.
Maps A map is an object that maps keys to values Each key can map to at most one value, and a map cannot contain duplicate keys KeyValue Map Examples Dictionaries:
Set, TreeSet, TreeMap, Comparable, Comparator. Def: The abstract data type set is a structure that holds objects and satifies ARC: Objects can be added.
CS-2851 Dr. Mark L. Hornick 1 Tree Maps and Tree Sets The JCF Binary Tree classes.
(c) University of Washingtonhashing-1 CSC 143 Java Hashing Set Implementation via Hashing.
Engr 691 Special Topics in Engineering Science Software Architecture Spring Semester 2004 Lecture Notes.
CS2110: SW Development Methods Textbook readings: MSD, Chapter 8 (Sect. 8.1 and 8.2) But we won’t implement our own, so study the section on Java’s Map.
Thought for the Day “To become truly great, one has to stand with people, not above them.” – Charles de Montesquieu.
Searching Also: Logarithms. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an.
1 Abstraction  Identify important aspects and ignore the details  Permeates software development programming languages are abstractions built on hardware.
Cs205: engineering software university of virginia fall 2006 Data Abstraction David Evans
CSE 143 Lecture 20 Binary Search Trees continued; Tree Sets read slides created by Marty Stepp and Hélène Martin
The Java Collections Framework (Part 2) By the end of this lecture you should be able to: Use the HashMap class to store objects in a map; Create objects.
EECE 310: Software Engineering Iteration Abstraction.
Puzzle 3 1  Write the class Enigma, which extends Object, so that the following program prints false: public class Conundrum { public static void main(String[]
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Effective C#, Chapter 1: C# Language Elements Last Updated: Fall 2011.
Some Other Collections: Bags, Sets, Queues and Maps COMP T2 Lecture 4 School of Engineering and Computer Science, Victoria University of Wellington.
Design Patterns Gang Qian Department of Computer Science University of Central Oklahoma.
Comparison-Based Sorting & Analysis Smt Genap
HashCode() 1  if you override equals() you must override hashCode()  otherwise, the hashed containers won't work properly  recall that we did not override.
Comparable and Comparator Nuts and Bolts. Sets A set is a collection in which all elements are unique—an element is either in the set, or it isn’t In.
Type Abstraction Liskov, Chapter 7. 2 Liskov Substitution Principle In any client code, if the supertype object is substituted by a subtype object, the.
Data Abstractions EECE 310: Software Engineering.
Type Abstraction SWE Spring October 05Kaushik, Ammann Substitution Principle “In any client code, if supertype object is substituted.
Csci 490 / Engr 596 Special Topics / Special Projects Software Design and Scala Programming Spring Semester 2010 Lecture Notes.
Effective Java: Methods Common to All Objects SWE 619: Fall 2008 Paul Ammann.
Copyright © 0 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with Java From Control Structures through Data Structures by Tony.
Data Abstraction SWE 619 Software Construction Last Modified, Spring 2009 Paul Ammann.
Iterators ITI 1121 N. El Kadri. Motivation Given a (singly) linked-list implementation of the interface List, defined as follows, public interface List.
Polymorphism SWE 619. Outline equals() Revisiting Liskov’s mutable vs. not rule Polymorphism Uniform methods for different types “easy” polymorphism Element.
Sets and Maps Part of the Collections Framework. 2 The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
Iteration Abstraction SWE Software Construction Fall 2009.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Data Structures in Java: From Abstract Data Types to the Java Collections.
Collections Dwight Deugo Nesa Matic
Type Hierarchies. Type Hieararchy Why?: Want to define family of related types. At the top of the hierarchy, a type whose spec defines behavior common.
(c) University of Washington20c-1 CSC 143 Binary Search Trees.
David Evans CS201J: Engineering Software University of Virginia Computer Science Lecture 5: Implementing Data Abstractions.
More constructors 1. Constructors  recall that a public constructor is what a client uses to create an object  the purpose of a constructor is to initialize.
Java Collections Framework The client view. The Big Picture.
EECE 310: Software Engineering
Polymorphism SWE 619, Last Updated Fall 2008.
Searching.
EECE 310: Software Engineering
Specifications Liskov Chapter 9
Type Abstraction SWE Spring 2009.
Iteration Abstraction
null, true, and false are also reserved.
Java Collections Framework
Type Abstraction Liskov, Chapter 7.
Iteration Abstraction
SWE 619 Software Construction Last Modified, Fall 2015 Paul Ammann
Lecture 4: Data Abstraction CS201j: Engineering Software
Chapter 9 Carrano Chapter 10 Small Java
CSC 143 Binary Search Trees.
Type Abstraction SWE Spring 2013.
CMPE212 – Reminders Assignment 2 due next Friday.
Presentation transcript:

Polymorphism Liskov 8

Outline equals() Revisiting Liskov’s mutable vs. not rule Polymorphism Uniform methods for different types “easy” polymorphism Element subtype approach Planning ahead Related subtype approach Reacting after the fact

A word about equals Problem: We want to check if two objects are equal to each other Many ways to do so: Object identity [A==B] (same object) Object state [A.counter = B.counter] (similar objects) Object property [A.area() = B.area()] (practically same)

Overriding equals Object class equals is ‘==‘ check Overriding equals means providing a check other than object identity. Usually it provides object state check Overriding equals in a mutable class A.equals(B) is true/false at different times Immutable classes don’t suffer from this problem

How to get in trouble: Storing mutable types in collections Assume a collection that does not allow duplicates (eg java.util.TreeSet) Aim: to store mutable types with overridden equals. void insert (Object x) { for all elements in collection{ if (element[i].equals(x)) return; // no duplicates } collection.addElement(x);

What’s the Problem? Consider client code for fig 8.1: Set s = new HashSet(); // AF(s) = {} Vector x = new Vector() // AF(x) = [] Vector y = new Vector() // AF(y) = [] s.insert(x); // AF(s) = {[]} s.insert(y); // AF(s) = {[], []}? Or {[]}? s.contains(y) // true or false? y.add(“cat”); // AF(y) = [“cat”] // AF(s) = ????? s.contains(y); // true or false? s.insert(y); // s.state = {[], [“cat”]}??? y.remove(“cat”); // s.state = {[], []} ??? !!!!

Liskov’s Solution Liskov’s approach to equals() avoids this problem Mutable objects compared via “==“ A workaround for Java’s decision public boolean equals (Object x) { if (!x instanceOf Container) return false; return (el == ((Container) x.el)); } Equality does not pose a problem anymore! We can insert both x and y in s. Even if x modified, we will still find y in s

Outline equals() Revisiting Liskov’s mutable vs. not rule Polymorphism Uniform methods for different types “easy” polymorphism Element subtype approach Planning ahead Related subtype approach Reacting after the fact

What is Polymorphism? Generalize abstractions They should work for many types E.g.: IntSet could be generalized to Set Not just store integers, but other data types Saves us from creating new data abstractions for each data type (like PolySet, FloatSet, etc.) Compare IntSet with HashSet, TreeSet

Polymorphic procedures Procedures can be polymorphic with respect to types of arguments E.g.: Intset.insert(int x) becomes Set.Insert(Object x) or overloaded Set.Insert(…) with the specified list of types How does this affect specs of procedures?

Polymorphic Data abstractions Two kinds: element subtype (Comparable, Addable) Pre planning. Unique way for all subtypes related subtype (Comparator, Adder) post planning, class designer did not provide it create a related type for each object type Both kinds use interfaces for generalization

Comparable Interface (fig 8.4) public interface Comparable { //O: Subtypes of Comparable provide a method to determine the ordering of their objects. This ordering must be a total order over their objects, and it should be both transitive and antisymmetric. Furthermore, x.compareTo(y)== 0 implies (iff???) x.equals(y). public int compareTo (T x) throws CCE, NPE; //E: If x is null, throws NPE; if this and x aren’t compatible, throws CCE. Otherwise, if this is less than x returns 0

OrderedList (Figure 8.5) Stores elements which implement Comparable interface Bug in addEl() (first line) “if (val == null)” should be “if (el == null)” Specs: order of exceptions! Very similar to TreeSet What is the abstract state?

Ordered List code (fig 8.5) public class OL { private boolean empty; private OL left, right; private Comparable val; public void addEl(Comparable el) throws NPE,DE,CCE // M: this // E: if el is null throw NPE else if el is in this throw DE else if el is incomparable to elements in this throw CCE else add el to this if (el == null) throw new NPE(...) if (empty) {left = new OL(); right = new OL(); val = el; empty = false; return;} int n = el.compareTo(val); if (n == 0) throw new DE(...); if(n < 0) left.addEl(el); else right.addEl(el); }

Related subtype approach After classes have been designed We want a collection to store and operate on any of such types Some client code may already exist! We don’t want it to break. So we create related subtype Accompanies each type, supports desired operations

Related subtype Example problem (figure 8.8): We want to sum up all the elements in a set. SumSet class must maintain a running sum of all Integers, Floats or Poly’s stored. We store one type of object at a time SumSet a  stores only Polys SumSet b  stores only Integers

SumSet Implementation (Fig 8.8) public class SumSet { private Vector els; private Object s; private Adder a; public SumSet(Adder p) throws NPE { els = new Vector(); a = p; s = p.zero();} public void insert(Object x) throws NPE, CCE { // M: this // E: if x is null throw NPE; if x cannot be added to this // throw CCE; else adds x to this and adjusts the sum Object z = a.add(s, x); if (!els.contains(x)) { els.add(x); s = z; } public Object sum() { //E: return sum of elements in this return s; } } Note order of exceptions What’s an “Adder”?

Comparator interface public interface Comparator { public int compare (T x, T y) throws NPE, CCE; //E: IF x,y = null, throws NPE; //If x and y are not comparable, throws CCE //If x less than y, returns -1; if x is equal to y, returns 0; if x greater than y, returns 1 } Why two parameters in compare()? How does client use it?

StringFromBackComparator String.compareTo(String) method provides a dictionary like ordering. (lexicographical ordering) What if we want a different ordering? For example: We want to compare strings from back. “cat”.comparison(“dog”) should return 1 We can achieve so by implementing our own Comparator: StringFromBackComparator (SFBC)

SFBC implementation public class SFBC implements Comparator { public int compare (String x, String y){ if (x==null || y == null) throw new NPE(); … //compare sx and sy from back.. }

How does client use SFBC? String n = “cat”; String p = “dog”; int m = (new SFBC()).compare(n,p); Or Set set = new TreeSet (new SFBC()); Iterator itr = set.iterator(); // AF (itr) = [dog, cat]

E.g.: ReverseComparator We are not satisfied by comparable.compareTo() method. We cannot change it! Alternate way: use Comparator to define our own criteria Here, we want to reverse the evaluation of Comparable.compareTo

Implementation public class RC > implements Comparator { //O: Reverse the natural order of elements. Eg: 7<3 here public int compare (T x, T y) throws NPE, CCE { return –x.compareTo(y); }

How about absolute comparison? public class AbsoluteComparator implements Comparator //O: Compare on absolute value of (Integer) elements public int compare (Integer a, Integer b) throws NPE, CCE { if (a < 0) a = -a; if (b < 0) b = -b; // absolute values if (a < b) return -1; if (a > b) return 1; return 0; } Is this correct?

Similarities between Comparable and Addable Comparable Provides uniform way to compare elements Abstracts from types All types compared in a similar manner Addable Provides uniform way to add elements Abstracts from types All types added in a similar manner