Engr 691 Special Topics in Engineering Science Software Architecture Spring Semester 2004 Lecture Notes.

Slides:



Advertisements
Similar presentations
Engr 691 Special Topics in Engineering Science Software Architecture Spring Semester 2004 Lecture Notes.
Advertisements

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.
OO Programming in Java Objectives for today: Overriding the toString() method Polymorphism & Dynamic Binding Interfaces Packages and Class Path.
METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
1 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
C12, Polymorphism “many forms” (greek: poly = many, morphos = form)
Comp 249 Programming Methodology Chapter 7 - Inheritance – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,
Inheritance Inheritance Reserved word protected Reserved word super
ACM/JETT Workshop - August 4-5, :Inheritance and Interfaces.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
1 Chapter 7 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
Polymorphism. Lecture Objectives To understand the concept of polymorphism To understand the concept of static or early binding To understand the concept.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Chapter 12: Adding Functionality to Your Classes.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
CSE 425: Object-Oriented Programming II Implementation of OO Languages Efficient use of instructions and program storage –E.g., a C++ object is stored.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Taken from slides of Starting Out with C++ Early Objects Seventh Edition.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Polymorphism Lecture-10. Print A Cheque A Report A Photograph PrintCheque() PrintReport() PrintPhoto() Printing.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
The Java Programming Language
1 COSC3557: Object-Oriented Programming Haibin Zhu, Ph. D. Associate Professor of CS, Nipissing University.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
CSCI-383 Object-Oriented Programming & Design Lecture 23.
Chapter 10 Defining Classes. The Internal Structure of Classes and Objects Object – collection of data and operations, in which the data can be accessed.
Types in programming languages1 What are types, and why do we need them?
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Session 24 Chapter 12: Polymorphism. Polymorphism polymorphism comes from the Greek root for “many forms” polymorphism is about how we can use different.
Csci 490 / Engr 596 Special Topics / Special Projects Software Design and Scala Programming Spring Semester 2010 Lecture Notes.
(1) ICS 313: Programming Language Theory Chapter 12: Object Oriented Programming.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Polymorphism CMPS Poly-morphism Means “many-forms” Means different things in biology, chemistry, computer science Means different things to functional.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Coming up: Inheritance
© 2004 Pearson Addison-Wesley. All rights reserved April 14, 2006 Polymorphism ComS 207: Programming I (in Java) Iowa State University, SPRING 2006 Instructor:
Csci 490 / Engr 596 Special Topics / Special Projects Software Design and Scala Programming Spring Semester 2010 Lecture Notes.
Ceg860 (Prasad)L17IT1 Inheritance Techniques Subcontracting Anchored Types.
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.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Classes, Interfaces and Packages
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
Overview of C++ Polymorphism
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
Copyright 2006 Pearson Addison-Wesley, 2008, 2012 Joey Paquet 1 Concordia University Department of Computer Science and Software Engineering SOEN6441 –
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 1: Computer Systems Presentation slides for Java Software Solutions for AP* Computer Science.
ISBN Chapter 12 Support for Object-Oriented Programming.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Polymorphic Variables CMPS2143. The Polymorphic Variable A polymorphic variable is a variable that can reference more than one type of object (that is,
CSCI 383 Object-Oriented Programming & Design Lecture 22 Martin van Bommel.
CSCI 383 Object-Oriented Programming & Design Lecture 21 Martin van Bommel.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Modern Programming Tools And Techniques-I
Object-oriented Programming in Java
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
Csci 490 / Engr 596 Special Topics / Special Projects Software Design and Scala Programming Spring Semester 2010 Lecture Notes.
Types of Programming Languages
Programming Language Concepts (CIS 635)
Java Programming Language
Polymorphism Polymorphism
9: POLYMORPHISM Programming Technique II (SCSJ1023) Jumail Bin Taliba
Overview of C++ Polymorphism
Presentation transcript:

Engr 691 Special Topics in Engineering Science Software Architecture Spring Semester 2004 Lecture Notes

Polymorphism (Budd's UOOPJ, Ch. 12) This is a set of "slides" to accompany chapter 12 of Timothy Budd's textbook Understanding Object-Oriented Programming with Java, Updated Edition (Addison-Wesley, 2000)

Definition Polymorphous: –Having, or assuming, various forms, characters, or styles (Webster's Collegiate Dictionary, Fifth Edition). Term used in several different ways in computer science

Polymorphism in Programming Languages A variable holding a value drawn from a group of types A name associated with several different function bodies A single function with polymorphic variables as parameters

Polymorphism in Untyped Languages Polymorphism is trivial issue in untyped languages All variables are potentially polymorphic Variables take on type of their values dynamically silly: x " a silly Smalltalk polymorphic method " " a silly Smalltalk polymorphic method " (x isKindOf: Integer) ifTrue: [ ^ x + 1 ]. (x isKindOf: Integer) ifTrue: [ ^ x + 1 ]. (x isKindOf: Fraction) ifTrue: [ ^ x reciprocal ]. (x isKindOf: Fraction) ifTrue: [ ^ x reciprocal ]. (x isKindOf: String) ifTrue: [ ^ x reversed ]. (x isKindOf: String) ifTrue: [ ^ x reversed ]. ^ nil ^ nil

Forms of Polymorphism polymorphic variables (assignment polymorphism) overloading (ad hoc polymorphism) overriding (inclusion polymorphism) deferred (abstract) methods pure polymorphism (functions with polymorphic parameters) generics or templates

Polymorphic Variables Variable declared as one class can hold values from subclass Dynamic (run-time) type must be subclass of static (declared) type In C++, only works with pointers and references Polymorphic variables (or values) basis for power of OOP

Overloading A single function name denoting two or more function bodies is overloaded Common example: + means both integer and floating addition In Java, + also used for string concatenation In Java, + also used for string concatenation Determination of which function to execute made by examining argument/return types Bound either at compile-time or at run-time depending on language Should not be confused with overriding or refinement – functions need not be related by classes Should not be confused with coercion (casting) – one type is converted into another for operation

Overloading Example: Florist class Spouse { public void sendFlowersTo(Address inAddress) public void sendFlowersTo(Address inAddress) { go to florist; go to florist; give florist message give florist message sendFlowersTo(anAddress); sendFlowersTo(anAddress); }}

Overloading Example: Florist class Florist { public void sendFlowersTo(Address anAddress) public void sendFlowersTo(Address anAddress) { if (address is nearby) if (address is nearby) { make up flower arrangement; make up flower arrangement; tell delivery person sendFlowersTo(anAddress); tell delivery person sendFlowersTo(anAddress); } else { } else { look up florist near anAddress; look up florist near anAddress; contact other florist; contact other florist; give other florist message sendFlowersTo(anAddress); give other florist message sendFlowersTo(anAddress); } }} Above the sendFlowersTo methods are semantically related but not related via inheritance Methods with same name not necessarily related semantically

Overloading and Type Signatures Selection of which procedure to execute based on type signature –the number, types, and order of parameters –parametric overloading Often used in constructors C++ and Java allow functions in same scope to have same name if signatures differ C++ also allows extensive overloading of operator symbols

Overloading and Type Signatures (continued) Polymorphic symbol << used for both left shift and stream output – latter also overloaded by type of value stream << integer; stream << integer; stream << char; stream << char; stream << char *; stream << char *; stream << double; stream << double; stream << complex; stream << complex;

Overriding Overriding occurs when child class changes meaning of function from parent Different child classes can override in different ways – replacement or refinement Parent class can have default behavior; child classes alternatives Contributes to code sharing Ensures common interfaces

Example: Comparisons abstract class Magnitude { public boolean lessOrEqual(Magnitude arg) public boolean lessOrEqual(Magnitude arg) throws IncomparableMagnitudeException { throws IncomparableMagnitudeException { return (this.lessThan(arg) || this.equals(arg)); return (this.lessThan(arg) || this.equals(arg)); } public boolean greaterOrEqual(Magnitude arg) public boolean greaterOrEqual(Magnitude arg) throws IncomparableMagnitudeException { throws IncomparableMagnitudeException { return arg.lessOrEqual(this); return arg.lessOrEqual(this); } public boolean lessThan(Magnitude arg) public boolean lessThan(Magnitude arg) throws IncomparableMagnitudeException { throws IncomparableMagnitudeException { return this.lessOrEqual(arg) && ! this.equals(arg); return this.lessOrEqual(arg) && ! this.equals(arg); } public boolean greaterThan(Magnitude arg) public boolean greaterThan(Magnitude arg) throws IncomparableMagnitudeException { throws IncomparableMagnitudeException { return arg.lessThan(this); return arg.lessThan(this); }}

Example: Comparisons (continued) class IncomparableMagnitudeException extends Exception { public IncomparableMagnitudeException() { } public IncomparableMagnitudeException() { } public IncomparableMagnitudeException(String msg) public IncomparableMagnitudeException(String msg) { super(msg); } { super(msg); }} To define all six comparisons in a noncircular manner, subclasses must: Override class Object method equals() if default not appropriate Override class Magnitude method lessThan() or lessOrEqual()

Example: Comparisons (continued) class Point extends Magnitude { public Point(int x0, int y0) public Point(int x0, int y0) { x = x0; y = y0; } { x = x0; y = y0; } public boolean lessThan(Magnitude arg) public boolean lessThan(Magnitude arg) throws IncomparableMagnitudeException { throws IncomparableMagnitudeException { if (arg instanceof Point) { if (arg instanceof Point) { Point p = (Point) arg; // less if lower left quadrant Point p = (Point) arg; // less if lower left quadrant return x < p.x && y < p.y; // of this point return x < p.x && y < p.y; // of this point } else throw new IncomparableMagnitudeException(); } else throw new IncomparableMagnitudeException(); } private int x; private int y; private int x; private int y;} Note: The above method uses inheritance by limitation because of the check for the Point type and throwing the exception

Deferred (Abstract) Methods Deferred method is special case of overriding Parent class gives type signature, but provides no implementation Child class must provide an implementation Usually combined with other techniques Method included in parent class because it fits in abstraction, although no concrete definition may be possible at that level  semantics of abstract methods should be specified carefully – e.g., using pre- and postconditions.  subclasses should adhere to specification Allows the deferred method to be applied to polymorphic variables of the parent type In Java, use abstract modifier for method

Pure Polymorphism Pure polymorphism usually means functions with polymorphic parameters (including receiver) Method between (like the other methods of Magnitude) exhibits pure polymorphism class Magnitude {... public boolean between(Magnitude low, Magnitude high) public boolean between(Magnitude low, Magnitude high) throws IncomparableMagnitudeException { throws IncomparableMagnitudeException { return low.lessOrEqual(this) && this.lessOrEqual(high); return low.lessOrEqual(this) && this.lessOrEqual(high); }} Works for any receiver or arguments of parent type Magnitude (generates exception if of incomparable types)

Pure Polymorphism (continued) Code below would print "Is Between" Point p = new Point(0,0); Point q = new Point(10,10); Magnitude r = new Point(0,0); if (r.between(p,q)) System.println("Is Between"); System.println("Is Between");else System.println System.println ("Is Not Between"); ("Is Not Between");

Pure Polymorphism (continued) Message r.between(p,q) has the following trace of dynamic binding:  In code above, checks for between() in Point, not found  In code above, checks for between() in Magnitude, found, binds call  In Magnitude.between, checks for lessOrEqual() in Point, not found  In Magnitude.between, checks for lessOrEqual() in Magnitude, found, binds call  In Magnitude.lessOrEqual, checks for lessThan() in Point, found, binds call  In Point.lessThan, returns false since (0,0) is not less than (0,0)  In Magnitude.lessOrEqual, checks for equals() in Point, not found  In Magnitude.lessOrEqual, checks for equals() in Magnitude, not found  In Magnitude.lessOrEqual, checks for equals() in Object, found, binds call  In Object.equals, returns true  In Magnitude.lessOrEqua l, returns true since (0,0) <= (0,0)  Similar for comparison of (0,0) and (10,10)...  In Magnitude.between, returns true since (0,0) <= (0,0) and (0,0) <= (10,10), l Note that polymorphism (dynamic binding) takes more execution time than a static binding

Generics and Templates A type can be used as a parameter in class description C++ example: template class Link { public: public: private: private: T value; T value; Link * nextLink; Link * nextLink;}

Generics and Templates (continued) Declaration of variable provides the actual type  Link sl;  Declaration above makes s1 a Link variable that has a value of type Shape Generics not supported in Java currently, but may be in the future  Keyword generic reserved  Experimental versions of Java do support generics

Review of Polymorphism in Java Polymorphic variables? Yes  Tree-structured subclass hierarchy using inheritance (extends)  Subtype hierarchies using interfaces (implements)  Variables declared with either class or interface as type  Variables can hold value from subclass or interface subtype Overloading? Yes  Overloading of method names (including in same class with parametric overloading)  No user-defined overloading of operator symbols

Review of Polymorphism in Java Overriding? Yes  By default, all methods can be overridden  Keyword final prevents overriding Deferred methods? Yes  Keyword abstract for deferred methods, signature but no body Pure polymorphism? Yes  Dynamic binding of call to method, searching up subclass hierarchy Generics? No  Perhaps in future  Experimental versions such as GJ (Generic Java)

Efficiency and Polymorphism Programming always involves compromises Polymorphism is a compromise between efficiency and ease of development, use and maintenance Ask yourself: whose time is more important –yours or the computer's?