1 COSC2767: Object-Oriented Programming Haibin Zhu, Ph. D. Associate Professor of CS, Nipissing University.

Slides:



Advertisements
Similar presentations
Lists and the Collection Interface Chapter 4. Chapter Objectives To become familiar with the List interface To understand how to write an array-based.
Advertisements

Containers CMPS Reusable containers Simple data structures in almost all nontrivial programs Examples: vectors, linked lists, stacks, queues, binary.
Object Oriented Programming with Java
OO Programming in Java Objectives for today: Overriding the toString() method Polymorphism & Dynamic Binding Interfaces Packages and Class Path.
1 COSC2767: Object-Oriented Programming Haibin Zhu, Ph. D. Associate Professor of CS, Nipissing University.
C12, Polymorphism “many forms” (greek: poly = many, morphos = form)
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
1 Templates and Friends Lesson #9 Note: CIS 601 notes were originally developed by H. Zhu for NJIT DL Program. The notes were subsequently revised by M.
1 L41 Collections (1). 2 OBJECTIVES  What collections are.  To use class Arrays for array manipulations.  To use the collections framework (prepackaged.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
Chapter 10 Classes Continued
Inheritance and Polymorphism CS351 – Programming Paradigms.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Computer Science and Software Engineering University of Wisconsin - Platteville 7. Inheritance and Polymorphism Yan Shi CS/SE 2630 Lecture Notes.
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.
OOP Languages: Java vs C++
Appendix A.2: Review of Java and Object-Oriented Programming: Part 2 “For the object-oriented project, remember that the primary unit of decomposition.
Engr 691 Special Topics in Engineering Science Software Architecture Spring Semester 2004 Lecture Notes.
Chapter 12: Adding Functionality to Your Classes.
LECTURE LECTURE 17 More on Templates 20 An abstract recipe for producing concrete code.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Polymorphism Lecture-10. Print A Cheque A Report A Photograph PrintCheque() PrintReport() PrintPhoto() Printing.
Generalized Containers CSIS 3701: Advanced Object Oriented Programming.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
1 COSC3557: Object-Oriented Programming Haibin Zhu, Ph. D. Associate Professor of CS, Nipissing University.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
CSSE501 Object-Oriented Development. Chapter 12: Implications of Substitution  In this chapter we will investigate some of the implications of the principle.
Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 5, page 1 Sun Certified Java 1.4 Programmer Chapter 5 Notes Gary Lance
APCS Java AB 2004 Review of CS1 and CS2 Review for AP test #1 Sources: 2003 Workshop notes from Chris Nevison (Colgate University) AP Study Guide to go.
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.
Case Study - Fractions Timothy Budd Oregon State University.
Generics and Collections. Introduction Generics New feature of J2SE 5.0 Provide compile-time type safety Catch invalid types at compile time Generic methods.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley. Ver Chapter 8: Class Relationships Data Abstraction & Problem Solving.
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.
Programming in Java CSCI-2220 Object Oriented Programming.
Types in programming languages1 What are types, and why do we need them?
Chapter 7 Templates. Objectives Introduction Function Templates Class Templates Standard Template Library.
Overview of C++ Templates
 Objects versus Class  Three main concepts of OOP ◦ Encapsulation ◦ Inheritance ◦ Polymorphism  Method ◦ Parameterized ◦ Value-Returning.
Csci 490 / Engr 596 Special Topics / Special Projects Software Design and Scala Programming Spring Semester 2010 Lecture Notes.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
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.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Slides prepared by Rose Williams, Binghamton University Chapter 16 Collections and Iterators.
Overview of C++ Polymorphism
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
Chapter 7 Constructors and Other Tools Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Chapter  Array-like data structures  ArrayList  Queue  Stack  Hashtable  SortedList  Offer programming convenience for specific access.
Polymorphic Variables CMPS2143. The Polymorphic Variable A polymorphic variable is a variable that can reference more than one type of object (that is,
Motivation for Generic Programming in C++
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Modern Programming Tools And Techniques-I
7. Inheritance and Polymorphism
COSC2767: Object-Oriented Programming
Inheritance and Polymorphism
Student Book An Introduction
CS212: Object Oriented Analysis and Design
Java Programming Language
CMSC 202 Lesson 22 Templates I.
Overview of C++ Polymorphism
Templates I CMSC 202.
Presentation transcript:

1 COSC2767: Object-Oriented Programming Haibin Zhu, Ph. D. Associate Professor of CS, Nipissing University

2 Lecture 8 u The Polymorphic Variable and Generics

3 Polymorphic variable u A polymorphic variable is a variable that can u hold values of different types during the course of execution.

4 Simple Polymorphic Variables u public class Solitaire { u... u static CardPile allPiles [ ]; u... u public void paint(Graphics g) { u for (int i = 0; i < 13; i++) u allPiles[i].display(g); u } u... u } u The variable was declared as CardPile, but actually held a number of different types.

5 The Receiver Variable u The most common polymorphic variable is the one that holds the receiver during the execution of a method. u Call this in C++ and Java, self in Smalltalk and Objective-C, current in Eiffel. u Holds the actual value (the dynamic class) during execution, not the static class.

6 The Receiver Variable in Frameworks u The greatest power of the receiver variable comes in the development of software frameworks. u In a framework, some methods are implemented in the parent class and not overridden (called foundation method), others are defined in the parent class, but intended to be overridden (called deferred method). u Consider a class Window with subclasses TextWindow and GraphicsWindow. u The combination of foundation and deferred methods allow high level algorithms to be reused and specialized in new situations.

7 Example, Repainting Window u class Window { u public void repaint () { u // invoke the deferred method paint. u // Because the implicit receiver, this, u // is polymorphic, the method from the u // child class will be executed u paint (graphicsContext); u } u abstract public void paint (Graphics g); // deferred u private Graphics graphicsContext; u } u class GraphicsWindow extends Window { u public void paint (Graphics g) { u // do the appropriate painting job u } u Window w= new GraphicsWindow(); u w.repaint(); u Only the child class knows how to paint the window. The receiver variable is responsible for remembering the actual class of the receiver when executing the method in the parent class.

8 Self and Super u In Java and Smalltalk there is another pseudo-variable, named super. u Super is like self, only when a message is given to super it looks for the method in the parent class of the current class. u class Parent { u void exampleOne () { u System.out.println("In parent method"); u } u class Child extends Parent { u void exampleOne () { u System.out.println("In child method"); u super.exampleOne(); u } u }//Super.java u Variable is called base in C#.

9 Downcast (Reverse Polymorphism) u It is sometimes necessary to undo the assignment to a polymorphic variable. u That is, to determine the variables true dynamic value, and assign it to a variable of the appropriate type. u This process is termed down casting, or, since it is undoing the polymorphic assignment, reverse polymorphism. u Various different syntaxes are used for this, see the book. u Parent aVariable =...; u Child aCard; u if (aVariable instanceof Child) u aChild = (Child) aVariable;

10 Pure Polymorphism u A polymorphic method (also called pure polymorphism) occurs when a polymorphic variable is used as an argument. Different effects are formed by using different types of value. u class StringBuffer { u String append (Object value) u { return append(value.toString()); } u... u }//PurePoly.java u Note: this is a non-stop method! u Different objects implement toString differently, so the effects will vary depending upon the argument.

11 Another Example of Pure Polymorphism u This example is from Smalltalk. u between: low and: high u ^ (low <= self) and: [ self <= high] u Different arguments will implement the relational test differently, so different effects can be achieved. u x between: $a and: $z u x between: 1 and: 100 u x between: 3.14 and: 4.56 u x between: "abc" and: "pdq" u x between: and:

12 Summary of Polymorphic Variables u A polymorphic Variable is a variable that can reference more than one type of object u Polymorphic variables derive their power from interaction with inheritance, overriding and substitution. u A common polymorphic variable is the implicit variable that maintains the receiver during the execution of a method u Downcasting is the undoing of a polymorphic assignment u Pure polymorphism occurs when a polymorphic variable is used as an argument.

13 Generics

14 Generics u The idea of a generic (or template) is yet another approach to software reuse. The time, the basic idea is to develop code by leave certain key types unspecified, to be filled in later. u In many ways this is like a parameter that is filled with many different values. Here, however, the parameters are types, and not values. u Generics are used both with functions and with classes.

15 Templates u Templates give us the means of defining a family of functions or classes that share the same functionality but which may differ with respect to the data type used internally. u A class template is a framework for generating the source code for any number of related classes. u A function template is a framework for generating related functions.

16 C++ Templates u Function template u Class template

17 Function Template template return-type function-name(T param) u //one parameter function. u T is called template parameter.

18 Function Templates u A function can be defined in terms of an unspecified type. u The compiler generates separate versions of the function based on the type of the parameters passed in the function calls.

19 C++ Template Functions u The following illustrates a simple template function in C++, and its use. u template T max(T left, T right) { u if (left < right) u return right; u return left; u } u int a = max(3, 27); u double d = max(3.14, 2.75); // see how types differ

20 One parameter function template u template u void Display(const T &val) u { cout << val; } u One parameter function with an additional parameters which are not template parameters u template u void Display(const T &val, ostream &os) u { os << val; } u The same parameter appear multiple times. u template u void Swap(T & x, T &y) u {... }

21 Swap swap Function Template Swap 2 integers Swap 2 floats Swap 2 rationals... generic

22 Swap #include template void Swap( TParam & x, TParam & y ) { TParam temp; temp = x; x = y; y = temp; }

23 Swap u class Student { u public: u Student( unsigned id = 0 ) u { u idnum = id; u } u int getID() {return idnum;}; u private: u unsigned idnum; u };

24 Swap int main() {int m = 10; int n = 20; Student S1( 1234 ); Student S2( 5678 ); cout << m<<" "<<n<<" "<<endl; Swap( m, n ); // call with integers cout << m<<" "<<n<<" "<<endl; cout << S1.getID()<<" "<<S2.getID()<<" "<<endl; Swap( S1, S2 ); // call with Students cout << S1.getID()<<" "<<S2.getID()<<" "<<endl; return 0; }//swap.cpp

25 Multiple parameter function template template void ArrayInput(T1 array, T2 & count) { for (T2 j= 0; j < count; j++) {cout << “value:”; cin >> array[j]; }

26 Multiple parameter function template const unsigned tempCount = 3; float temperature[tempCount ]; const unsigned stationCount = 4; int station[stationCount ]; ArrayInput(temperature, tempCount); ArrayInput(station, stationCount);

27 Example:Table Lookup #include template long indexOf( T searchVal, const T * table, unsigned size ) { for( unsigned i=0; i < size; i++ ) if( searchVal == table[i] ) return i; return -1; }

28 Example:Table Lookup int main() { const unsigned iCount = 10; const unsigned fCount = 5; int iTable[iCount] = { 0,10,20,30,40,50,60,70,80,90 }; float fTable[fCount] = { 1.1, 2.2, 3.3, 4.4, 5.5 }; cout << indexOf( 20, iTable, iCount ) << endl; // "2" cout << indexOf( 2.2f, fTable, fCount ) << endl; // "1" const unsigned sCount = 5; char * names[sCount] = { "John","Mary","Sue","Dan","Bob" }; cout << indexOf( "Dan", names, sCount )<<endl; // ? return 0; }//funtemplate.cpp

29 Note u In the function template, if you use a operator, you must be sure every class relevant to the template will support the operator, such as “==“, etc. u Therefore, C++ provides the mechanism of operator overloading.

30 Example: student class Student { public: Student( long idVal ) { id = idVal; } int operator ==( const Student & s2 ) const { return id == s2.id; } private: long id; // student ID number };

31 Example: student int main() { const unsigned sCount = 5; Student sTable[sCount] = { 10000, 11111, 20000, 22222, }; Student s( ); cout << indexOf( s, sTable, sCount )<<endl; // print "3" return 0; }//student.cpp

32 Overriding a Function Template u In some cases when the function template does not apply to a particular type, it may be necessary to either u override the function template, or u make the type conformant to the function template.

33 The best matching principle u Find a function that matches the parameters well; u If there is no match for a specific function, find a function template to check if the parameters match one specialized form; and u If no match is found, the call is declared as an erroneous one. u If it ends up with two or more equally good matches, the call is ambiguous and an error is also reported.

34 Class Template u Declare and define an object: template class MyClass{ //... } MyClass x; MyClass aStudent;

35 Template Classes u While template functions are useful, it is more common to use templates with classes. u template class Box { u public: u Box (T initial) : value(initial) { } u T getValue() { return value; } u setValue (T newValue) { value = newValue; } u private: u T value; u };

36 Can Be Filled with Different Arguments u Box iBox(7); u iBox.setValue(3.1415); u // ERROR - invalid type u Box dBox(2.7); u cout << dBox.getValue();//2.7 u dBox.setValue(3.1415); u cout << dBox.getValue();// u iBox = dBox; u // ERROR - mismatched types u In the next chapter we will see how generics are used to create collection classes.

37 Simple Example template class Circle { //... private: T1 x, y; T2 radius; }; //... Circle c1; Circle c2;

38 Class Template Array Class Template integer Array float Array FString Array... generic

39 Example: Array Class Template template class Array { public: Array( unsigned sz ); ~Array(); T & operator[]( unsigned i ); private: T * values; unsigned size; };

40 Example: Array Class Template template Array ::Array( unsigned sz ) { values = new T [sz]; size = sz; } template T & Array ::operator[] ( unsigned i ) { if( i >= size ) throw RangeError(__FILE__,__LINE__,i); return values[i]; } template Array ::~Array() { delete [] values;}

41 Example: Array Class Template int main() { const unsigned numDives = 2; Array diveNum( numDives ); Array difficulty( numDives ); Array diveName (numDives); int j; for(j = 0; j < numDives; j++) {cout << "Enter dive #, difficulty level, dive name "; cin >> diveNum[j] >> difficulty[j] >> ws; diveName[j].GetLine( cin ); } for(j = 0; j < 2; j++) cout << diveName[j] << '\n'; cout << endl; return 0; }//array.cpp, Fstring.cpp, Fstring.h, range.h, array.h

42 Templates and Inheritances u Template is not a class u No inheritances for a template u A class based on a template is an ordinary class u class t1 : public Array u {...}//OK!!! u templat u class Myclass: public Array u {//OK!!! u }

43 Inheritance and Generics u Remember the class Box. Suppose a class Person has subclasses BoyChild and GirlChild. What is the relationship between Box and Box ? u Unfortunately, runs into problems with the principle of substitution. u Assume Box is a subclass of Box, would make the following legal: u Box aBox = new Box ; u Person aGirl = new GirlChild; u aBox.set(aGirl); u A similar argument can be made for the reverse.

44 Inheritance and Arrays u Can make a similar argument for arrays: u BoyChild [ ] boys = new BoyChild[10]; u Person [ ] people = boys; // copy or pointer semantics? u GirlChild sally = new GirlChild; u people[1] = sally; u If pointer semantics are used for the array assignment then this can produce type errors. Java allows the assignment, but uses a run-time check to catch the last assignment error! u Other languages make the array assignment illegal.

45 Templates and static members u Keep in mind again: u Template is not class, only template. u Static members defined in a template are static members of the classes of this template.

46 Java Generics u List u ArrayList u LinkedList u Vector

47 Java List u A List (sometimes called a sequence) is an ordered Collection that can contain duplicate elements. u Like array indices, List indices are zero based (i.e., the first element’s index is zero). u In addition to the methods inherited from Collection, List provides methods for manipulating elements via their indices, manipulating a specified range of elements, searching for elements and getting a ListIterator to access the elements.searching u Interface List is implemented by several classes, including classes ArrayList, LinkedList and Vector.

48 ArrayList and LinkedList u Class ArrayList and Vector are resizable-array implementations of List. u Class LinkedList is a linked-list implementation of interface List. u Class ArrayList’s behavior and capabilities are similar to those of class Vector. u The primary difference between Vector and ArrayList is that objects of class Vector are synchronized by default, whereas objects of class ArrayList are not. u //CollectionTest.java u //ListTest.java

49 ListIterator u An iterator for lists that allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the iterator's current position in the list. u A ListIterator has no current element; its cursor position always lies between the element that would be returned by a call to previous() and the element that would be returned by a call to next(). u In a list of length n, there are n+1 valid index values, from 0 to n, inclusive. u Note that the remove() and set(Object) methods are not defined in terms of the cursor position; they are defined to operate on the last element returned by a call to next() or previous().remove()set(Object)next()previous()

50 Vector u Like ArrayList, class Vector provides the capabilities of array-like data structures that can resize themselves dynamically. u Recall that class ArrayList’s behavior and capabilities are similar to those of class Vector, except that ArrayLists do not provide synchronization by default. We cover class Vector here primarily because it is the superclass of class Stack. u At any time, a Vector contains a number of elements that is less than or equal to its capacity. The capacity is the space that has been reserved for the Vector’s elements. If a Vector requires additional capacity, it grows by a capacity increment that you specify or by a default capacity increment. If you do not specify a capacity increment or specify one that is less than or equal to zero, the system will double the size of a Vector each time additional capacity is needed.system u //VectorTest.java

51 Summary u Polymorphic variable u Self, super, this, base u Generics u Parameterized classes or functions u Template in C++ u Function template u Class template u Java Generics u List u ArrayList u LinkedList u Vector

52 Can Even Be Used with User Defined Types u class Fraction { u public: u Fraction (int top, int bottom) { t = top; b = bottom; } u int numerator() { return t; } u int denominator() { return b; } u bool operator < (Fraction & right) u { return t * right.b < right.t * b; } u private: u int t, b; u }; u Fraction x(3, 4); u Fraction y(7, 8); u Fraction z = max(x, y); u //fraction.cpp