Generic programming POLYMORPHISM 10/25/13

Similar documents
Chair of Software Engineering Java and C# in Depth

301AA - Advanced Programming [AP-2017]

Programming Languages and Techniques (CIS120)

Java: introduction to object-oriented features

Example: Count of Points

Atelier Java - J1. Marwan Burelle. EPITA Première Année Cycle Ingénieur.

Programming Languages and Techniques (CIS120)

Inheritance and Polymorphism

Type Hierarchy. Lecture 6: OOP, autumn 2003

Programming Languages and Techniques (CIS120)

Java 8 Programming for OO Experienced Developers

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

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

Java Fundamentals (II)

ITI Introduction to Computing II

Programming Languages and Techniques (CIS120)

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Example: Count of Points

ITI Introduction to Computing II

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

Chapter 5 Object-Oriented Programming

25. Generic Programming

Encapsula)on, cont d. Polymorphism, Inheritance part 1. COMP 401, Spring 2015 Lecture 7 1/29/2015

Inheritance and delega9on

Programming Languages and Techniques (CIS120)

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

Practice for Chapter 11

Programming Languages and Techniques (CIS120)

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

Principles of Software Construction: Objects, Design and Concurrency. Inheritance, type-checking, and method dispatch. toad

Inheritance and Polymorphism

Inheritance (cont.) Inheritance. Hierarchy of Classes. Inheritance (cont.)

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

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

15CS45 : OBJECT ORIENTED CONCEPTS

Classes and Inheritance Extending Classes, Chapter 5.2

Java Object Oriented Design. CSC207 Fall 2014

Programming Languages and Techniques (CIS120)

More Relationships Between Classes

Objects. Prof. Clarkson Fall ob-ject: to feel distaste for something Webster's Dictionary. Today s music: Kung Fu Fighting by CeeLo Green

Computer Science II (20073) Week 1: Review and Inheritance

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

Featherweight Java (FJ)

CMSC 132: Object-Oriented Programming II

Language Features. 1. The primitive types int, double, and boolean are part of the AP

1 Shyam sir JAVA Notes

Administrivia. Java Review. Objects and Variables. Demo. Example. Example: Assignments

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Instance Members and Static Members

Computer Science 210: Data Structures

CONSTRUCTOR & Description. String() This initializes a newly created String object so that it represents an empty character sequence.

Binghamton University. CS-140 Fall Dynamic Types

Fast Track to Core Java 8 Programming for OO Developers (TT2101-J8) Day(s): 3. Course Code: GK1965. Overview

INSTRUCTIONS TO CANDIDATES

The Java Programming Language

G Programming Languages - Fall 2012

First IS-A Relationship: Inheritance

Objects, Subclassing, Subtyping, and Inheritance

C++ Important Questions with Answers

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism.

CS-202 Introduction to Object Oriented Programming

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

Compiler Construction Lent Term 2015 Lectures 10, 11 (of 16)

Harvard School of Engineering and Applied Sciences Computer Science 152

Java Class Design. Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding

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

(800) Toll Free (804) Fax Introduction to Java and Enterprise Java using Eclipse IDE Duration: 5 days

Subtyping. Lecture 13 CS 565 3/27/06

Overloading, Type Classes, and Algebraic Datatypes

Programming Languages and Techniques (CIS120)

2. The object-oriented paradigm!

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

ob-ject: to feel distaste for something Webster's Dictionary

Class, Variable, Constructor, Object, Method Questions

CS558 Programming Languages

Inheritance -- Introduction

Charlie Garrod Bogdan Vasilescu

Lecture 4: Extending Classes. Concept

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

Programming Languages and Techniques (CIS120)

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

Thinking Induc,vely. COS 326 David Walker Princeton University

Compaq Interview Questions And Answers

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Agenda. Excep,ons Object oriented Python Library demo: xml rpc

Exercise 6 Multiple Inheritance, Multiple Dispatch and Linearization November 4, 2016

COMP 110/L Lecture 19. Kyle Dewey

FAQ: Classes & Objects

Some instance messages and methods

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

PROGRAMMING LANGUAGE 2

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

Introducing Java. Introducing Java. Abstract Classes, Interfaces and Enhancement of Polymorphism. Abstract Classes

F I N A L E X A M I N A T I O N

Java Primer 1: Types, Classes and Operators

Introduction to Programming Using Java (98-388)

Architecture of so-ware systems

IST311. Advanced Issues in OOP: Inheritance and Polymorphism

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Transcription:

POLYMORPHISM Generic programming! Code reuse: an algorithm can be applicable to many objects! Goal is to avoid rewri:ng as much as possible! Example: int sqr(int i, int j) { return i*j; double sqr(double i, double j) {return i*j;! The no:on of sqr is unique but we must define it twice because of types! Programming languages offer mechanisms to address this problem 1

Polymorphism! Polymorphism (Greek for many forms ) is the ability for code to be used with values of different types.! For example, a polymorphic func:on is one that can be invoked with arguments of different types.! A polymorphic datatype is one that can contain elements of different types. FORMS OF POLYMORPHISM 2

Subtype Polymorphism! Subtype polymorphism allows a term to have many types using the subsump:on rule (inheritance).! A func:on with argument τ can operate on any value with a type that is a subtype of τ. Ad Hoc Polymorphism! Ad- hoc polymorphism usually refers to code that appears to be polymorphic to the programmer, but the actual implementa:on is not.! A typical example is overloading: using the same func:on name for func:ons with different kinds of parameters. 3

Ad hoc polymprphism! There are actually mul:ple func:on implementa:ons (none being polymorphic) and the compiler invokes the appropriate one.! Ad- hoc polymorphism is a dispatch mechanism: the type of the arguments is used to determine (either at compile :me or run :me) which code to invoke. Parametric Polymorphism! Parametric polymorphism refers to code that is wripen without knowledge of the actual type of the arguments; the code is parametric in the type of the parameters.! Examples include polymorphic func:ons in ML (F#) and Java (C#) generics. 4

ML let rec map f l = match l with [] -> [] x::xs -> f(x) :: map f xs;; val map : ('a -> 'b) -> 'a list -> 'b list = <fun> map (function x -> x*10) [4;2;7];; - : int list = [40; 20; 70] ML let square = (fun x -> x*x) ;; val square : int -> int = <fun> Q: Why? 5

public class Point { protected final int x, y; private final String name; public Point(int x, int y){ this.x = x; this.y = y; name = makename(); Java protected String makename() { return "["+x+", "+y+"]"; public final String tostring() { return name; public class ColorPoint extends Point{ private final String color; public ColorPoint(int x, int y, String color){ super(x,y); this.color = color; protected String makename() { return super.makename() + ":" + color; public static void main(string [] args) { System.out.println(new ColorPoint(4, 2, "viola")); Q: What is program behaviour? public class Point { protected final int x, y; private final String name; public Point(int x, int y){ this.x = x; this.y = y; name = makename(); Java protected String makename() { return "["+x+", "+y+"]"; public final String tostring() { return name; public class ColorPoint extends Point{ private final String color; public ColorPoint(int x, int y, String color){ super(x,y); this.color = color; protected String makename() { return super.makename() + ":" + color; public static void main(string [] args) { System.out.println(new ColorPoint(4, 2, "viola")); Q: What is program behaviour? [4, 2]:null 6

Java(C#) Polymorphic Assignment! Let S be an ancestor of T! T is a subclass of S in the hierarchy! Upcas:ng: an object of type T is apached to a reference of type S! Downcas:ng: an object of type S is apached to a reference of type T! class Vehicle; class Car extends Vehicle; // car is a subtype of Vehicle Vehicle v =(Vehicle) new Car(); // upcas:ng Car c = (Car)new Vehicle(); // downcas:ng Cas:ng in Java! Upcas:ng is implicit o For primi:ve types, upcas:ng means assigning a smaller type to a larger compa:ble type " byte to short to int to long to float to double (long to float may actually lose precision) o For reference types, upcas:ng means assigning a subtype to a supertype, that is: " a subclass to superclass " an implementa:on of an interface X to that interface X " an interface X to the implementa:on of an ancestor of X! Downcas:ng must be explicit o can raise run:me excep:ons if it turns out to be impossible o No casts are allowed for reference types outside the inheritance hierarchy 7

Containers! Java Vector Vector v = new Vector(); v.addelement("pippo"); v.addelement(new Integer(2));! Vector API: Signature of addelement: void addelement(object x);! The argument has type Object because the container may contain any type of object Programming issues! Inser:ng an object in a vector we loose type informa:on! In our example we implicitly upcast from String to Object: v.addelement("pippo");! Extrac:ng the element with the wrong cast produces a run:me error: Integer i = (Integer)v.elementAt(0); 8

Programming Issues 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 opera:ons and arrays: opera:on available on all objects Sort Method 9

Abstract as much as possible! Itera:ng over a collec:on Interface 10

Enumerator for Vector class VectorEnum implements Enumeration { int idx; Vector v; bool hasmoreelements() { idx < v.size(); Object nextelement() { return v.elementat(idx++); VectorEnum(Vector v) { idx = 0; this.v = v;? Is the enumerator up to date? 11

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

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

Alterna:ve Java JDBC! Java DataBase Connec:vity is a specifica:on from Sun for accessing databases in Java! Interes:ng example of generic programming! It implements a driver architecture exploi:ng the mechanisms of JVM 14

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