Polymorphism Giuseppe Attardi Antonio Cisternino.

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming Lecture 10 API Review; Where Next.
Advertisements

Containers CMPS Reusable containers Simple data structures in almost all nontrivial programs Examples: vectors, linked lists, stacks, queues, binary.
Design Patterns CMPS Design Patterns Consider previous solutions to problems similar to any new problem ▫ must have some characteristics in common.
Chapter 10 Introduction to Arrays
1 Objects and ClassesStefan Kluth 1.6Objects and Classes 1.6What is an Object? 1.7Objects and Classes 1.8Object Interface, Class Inheritance, Polymorphism.
ITEC200 – Week03 Inheritance and Class Hierarchies.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Java Programming, 3e Concepts and Techniques Chapter 5 Arrays, Loops, and Layout Managers Using External Classes.
Giuseppe Attardi Antonio Cisternino
Copyright W. Howden1 Lecture 15: Generalization, Polymorphism and States.
1 Design patterns Lecture 4. 2 Three Important skills Understanding OO methodology Mastering Java language constructs Recognizing common problems and.
Review CSC 171 FALL 2004 LECTURE 21. Topics Objects and Classes Fundamental Types Graphics and Applets Decisions Iteration Designing Classes Testing and.
More OOP Design Patterns
Types in programming languages What are types, and why do we need them? Types in programming languages1.
CSE 332: C++ templates and generic programming I Motivation for Generic Programming in C++ We’ve looked at procedural programming –Reuse of code by packaging.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
OOP Languages: Java vs C++
Comparison of OO Programming Languages © Jason Voegele, 2003.
Event Handling in Java: Alternatives and Patterns Raja Sooriamurthi Information Systems Department Kelley School of Business Indiana.
1 Inheritance and Polymorphism Chapter 9. 2 Polymorphism, Dynamic Binding and Generic Programming public class Test { public static void main(String[]
Java Programming: Advanced Topics 1 Collections and Wealth of Utilities.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Sadegh Aliakbary Sharif University of Technology Fall 2011.
Chapter 3 Introduction to Collections – Stacks Modified
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Java2C# Antonio Cisternino Part II. Outline Array types Enum types Value types  differences from classes  boxing and unboxing Delegate types  Base.
C# Programming Fundamentals of Object-Oriented Programming Fundamentals of Object-Oriented Programming Introducing Microsoft.NET Introducing Microsoft.NET.
Polymorphism, Inheritance Pt. 1 COMP 401, Fall 2014 Lecture 7 9/9/2014.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Learning objectives By the end of this lecture you should be able to:  have a well-earned rest! Ch 24 Beyond the second semester.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
Patterns in programming 1. What are patterns? “A design pattern is a general, reusable solution to a commonly occurring problem in software. A design.
Programming Languages and Paradigms Object-Oriented Programming.
Chapter 2 Introducing Interfaces Summary prepared by Kirk Scott.
C# EMILEE KING. HISTORY OF C# In the late 1990’s Microsoft recognized the need to be able to develop applications that can run on multiple operating system.
Refactoring 2. Admin Blackboard Quiz Acknowledgements Material in this presentation was drawn from Martin Fowler, Refactoring: Improving the Design of.
Types in programming languages1 What are types, and why do we need them?
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
Java Basics Opening Discussion zWhat did we talk about last class? zWhat are the basic constructs in the programming languages you are familiar.
Design Patterns David Talby. This Lecture Re-routing method calls Chain of Responsibility Coding partial algorithms Template Method The Singleton Pattern.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
Design Patterns Software Engineering CS 561. Last Time Introduced design patterns Abstraction-Occurrence General Hierarchy Player-Role.
CMSC 330: Organization of Programming Languages Java Generics.
Introduction to Object-Oriented Programming Lesson 2.
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
Programmeren 1 6 september 2010 HOORCOLLEGE 2: INTERACTIE EN CONDITIES PROGRAMMEREN 1 6 SEPTEMBER 2009 Software Systems - Programming - Week.
Basics of JDBC Session 14.
Chapter 18 Object Database Management Systems. Outline Motivation for object database management Object-oriented principles Architectures for object database.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
April 20, 1998CS102-02Lecture 4-1 A Method to the Madness CS Lecture 4-1 Java's Work Horses.
Java How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Slides prepared by Rose Williams, Binghamton University Chapter 20 Java Never Ends.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Collections Dwight Deugo Nesa Matic
Session 7 More Implications of Inheritance & Chapter 5: Ball World Example.
(C) 2010 Pearson Education, Inc. All rights reserved. Java How to Program, 8/e.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Java for android Development Nasrullah Khan. Using instanceof in Android Development the classes such as Button, TextView, and CheckBox, which represent.
Object Oriented Programming Some Interesting Genes.
Patterns in programming
Modern Programming Tools And Techniques-I
Inheritance and Polymorphism
Java Primer 1: Types, Classes and Operators
Functional Programming with Java
.NET and .NET Core 5.2 Type Operations Pan Wuming 2016.
Java Programming Language
Abstract Class As per dictionary, abstraction is the quality of dealing with ideas rather than events. For example, when you consider the case of ,
Java Programming Language
Presentation transcript:

Polymorphism Giuseppe Attardi Antonio Cisternino

Generic programming Code reuse is clearly a good idea Code reuse is clearly a good idea Often an algorithm can be applicable to many objects Often an algorithm can be applicable to many objects Goal is to avoid rewriting as much as possible Goal is to avoid rewriting as much as possible Types introduce great benefits but also may limit code reuse: Types introduce great benefits but also may limit code reuse: int sqr(int i, int j) { return i*j; } double sqr(double i, double j) {return i*j; } The notion of sqr is unique but we must define it twice because of types The notion of sqr is unique but we must define it twice because of types Languages offer mechanisms to address this problem Languages offer mechanisms to address this problem

Polymorphism The ability of associate more than one meaning to a name in a program The ability of associate more than one meaning to a name in a program We have already seen two kinds of polymorphism: We have already seen two kinds of polymorphism: –Subtype/inclusion (inheritance) –Overloading Polymorphism is the fundamental mechanism for generic programming Polymorphism is the fundamental mechanism for generic programming There are other kinds of polymorphism There are other kinds of polymorphism

Classification of Polymorphism Polymorphism Universal Ad hoc Parametric Inclusion Overloading Coercion

Universal vs. ad hoc polymorphism With overloading an implementation for each signature is required With overloading an implementation for each signature is required We provide ad hoc solutions for different objects We provide ad hoc solutions for different objects Inheritance instead allows defining algorithms that operate on all classes of objects that inherit from a given class Inheritance instead allows defining algorithms that operate on all classes of objects that inherit from a given class In this case a single (universal) solution applies to different objects In this case a single (universal) solution applies to different objects

Implementing Polymorphism Dynamic method dispatch Dynamic method dispatch C++ adds a v-table to each object from a class having virtual methods C++ adds a v-table to each object from a class having virtual methods

Containers Example: Java Vector Example: Java Vector Vector v = new Vector(); v.addElement("Pippo"); v.addElement(new Integer(2)); Signature of addElement: Signature of addElement: void addElement(Object x); The argument is of type Object because the container may contain any type of object The argument is of type Object because the container may contain any type of object

Problem with containers Inserting an object in a vector we loose type information Inserting an object in a vector we loose type information In our example we implicitly upcast from String to Object: In our example we implicitly upcast from String to Object: v.addElement("Pippo"); Extracting the second element with the wrong cast produces a runtime error: Extracting the second element with the wrong cast produces a runtime error: Integer i = (Integer)v.elementAt(0);

Weakest constraint programming Where do we assume something about objects that we manipulate? Where do we assume something about objects that we manipulate? class Vector { Object[] v; int size; public Vector() { v = new Object[15]; size = 0; } public addElement(Object e) { if (size == v.length) { Object[] w = new Object[](2 * size); w.copy(v, 0, size); v = w; } v[size++] = e; }} We assume only assignment operations and arrays: operation available on all objects We assume only assignment operations and arrays: operation available on all objects

Can we sort our vector? How to add a method for sorting a vector? How to add a method for sorting a vector? We do not have enough information on our objects: no comparison operation is available We do not have enough information on our objects: no comparison operation is available Our vector is too generic! Our vector is too generic! Two solutions: Two solutions: –accept only objects that implement an interface (i.e. IComparable) that exposes a method to compare objects public void addElement(IComparable e) {…} –Pass a functional object: an object which implements an interface for comparing Object instances (i.e. IComparator) public void Sort(IComparator c) {…} interface IComparator { int compare(Object x, Object y); }

Abstract as much as possible! To express generic code with subtype polymorphism we should abstract the essence of the operations required on the objects we want to manipulate To express generic code with subtype polymorphism we should abstract the essence of the operations required on the objects we want to manipulate Risk is over-abstraction: once defined our vector we can’t easily add a sort method Risk is over-abstraction: once defined our vector we can’t easily add a sort method Another issue: inheritance relies on explicit annotation of our types and changes are hard to perform Another issue: inheritance relies on explicit annotation of our types and changes are hard to perform

Iterating over a collection A common programming pattern is to enumerate the elements of a collection A common programming pattern is to enumerate the elements of a collection It doesn’t really matter how the collection is organized It doesn’t really matter how the collection is organized We can implement a class per collection type whose objects enumerates the elements. We can implement a class per collection type whose objects enumerates the elements. Example: Example: Enumeration elements() { return ???; } void printCollection(Enumeration e) { while (e = hasMoreElements()) { Object o = e.nextElement(); System.out.println(o); }} Interface

Question Which class implements method elements? Which class implements method elements? –Class Vector –Use overloading and singleton class Enumeration { static Enumeration getEnumeration(Vector v){ return v.elements(); } // Other collections’ enumerators } Thus we can add enumerators to existing collections Thus we can add enumerators to existing collections

Enumerator for Vector class VectorEnum implements Enumeration { int idx; int idx; Vector v; Vector v; bool hasMoreElements() { idx < v.size(); } bool hasMoreElements() { idx < v.size(); } Object nextElement() { Object nextElement() { return v.elementAt(idx++); return v.elementAt(idx++); } VectorEnum(Vector v) { VectorEnum(Vector v) { idx = 0; idx = 0; this.v = v; // why it is not copied? this.v = v; // why it is not copied? }}

Is the enumerator up to date? To ensure that the enumerator is consistent the vector should be copied into the enumerator To ensure that the enumerator is consistent the vector should be copied into the enumerator This isn’t reasonable: memory wasted and we iterate on a different vector! This isn’t reasonable: memory wasted and we iterate on a different vector! There is no way to ensure that the enumerator is consistent with the vector There is no way to ensure that the enumerator is consistent with the vector Possible solution: introduce a “version” of the vector Possible solution: introduce a “version” of the vector Each time the vector is modified the version is incremented Each time the vector is modified the version is incremented Enumerator compares the version of the vector with the one at time of creation Enumerator compares the version of the vector with the one at time of creation

Event handling in GUI Before Java 1.1 OO GUI frameworks were based on sub-typing Before Java 1.1 OO GUI frameworks were based on sub-typing GUI can be easily described using generic programming: buttons are a subtype of control which is a special window GUI can be easily described using generic programming: buttons are a subtype of control which is a special window Containers of graphical widgets operates on controls, irrespective of their types Containers of graphical widgets operates on controls, irrespective of their types Event dispatching and handling is dealt by virtual methods Event dispatching and handling is dealt by virtual methods –hence by default is delegated to the super-type

Java AWT Event Model class Component { int x, y; int x, y; bool handleEvent(Event e); bool handleEvent(Event e);} class Button extends Component { String text; String text; bool handleEvent(Event e) { } bool handleEvent(Event e) { } …} class Window extends Component { … } class Frame extends Window { … }

Event handling class MyButton extends Button { boolean handleEvent(Event e) { switch (e.type) { case Event.MOUSE_UP: … return true; // Event handled! return true; // Event handled!}default: return super.handleEvent(e); return super.handleEvent(e);}}

Limits of AWT Event Model Generic programming in this case is quite elegant but inefficient Generic programming in this case is quite elegant but inefficient Propagation of events to a number of handlers, mostly useless Propagation of events to a number of handlers, mostly useless Proliferation of classes: one for each object with different behavior Proliferation of classes: one for each object with different behavior

Alternative Event Delegation model Event Delegation model Observer Pattern (aka publish/subscribe) Observer Pattern (aka publish/subscribe) Observable has set of registered observers Observable has set of registered observers Observable notifies its observers when its state changes Observable notifies its observers when its state changes Handling performed by objects that provide a Listener interface (aka callback, delegate) Handling performed by objects that provide a Listener interface (aka callback, delegate)

Java JDBC Java DataBase Connectivity is a specification from Sun for accessing databases in Java Java DataBase Connectivity is a specification from Sun for accessing databases in Java Interesting example of generic programming Interesting example of generic programming It implements a driver architecture exploiting the mechanisms of JVM It implements a driver architecture exploiting the mechanisms of JVM

Overall architecture The java.sql package exposes only interfaces The java.sql package exposes only interfaces The only class is DriverManager The only class is DriverManager Using the class constructor a driver register itself with the DriverManager Using the class constructor a driver register itself with the DriverManager The programmer performs the following steps: The programmer performs the following steps: –Load the database driver (a Java class) –Create a connection to a database (using DriverManager) –Obtain a Statement and execute the query –Enumerate the rows using a ResultSet

JDBC example Class.forName("…"); // Load the driver Connection c = DriverManager.getConnection("…"); Statement s = c.createStatement(); ResultSet r = s.executeQuery("select …"); while (r.hasNext()) { // Value of second column as String // Value of second column as String String s = r.getString(2); String s = r.getString(2);}

Question Statement is Class or Interface? Statement is Class or Interface? Connection, Statement are Interfaces Connection, Statement are Interfaces Through the DriverManager the program obtains an object of unknown type which implements the Connection interface Through the DriverManager the program obtains an object of unknown type which implements the Connection interface The same applies to all the other interfaces: through the connection an object implementing Statement is obtained, and so on and so forth The same applies to all the other interfaces: through the connection an object implementing Statement is obtained, and so on and so forth