COSC 2767 ObjectOriented Programming Haibin Zhu Ph D
COSC 2767: Object-Oriented Programming Haibin Zhu, Ph. D. Associate Professor of CS, Nipissing University 1
Lecture 8 u The Polymorphic Variable and Generics 2
Polymorphic variable u. A polymorphic variable is a variable that can u hold values of different types during the course of execution. 3
Simple Polymorphic Variables u u public class Solitaire {. . . static Card. Pile all. Piles [ ]; . . . public void paint(Graphics g) { for (int i = 0; i < 13; i++) all. Piles[i]. display(g); }. . . u u u 4 u } u The variable was declared as Card. Pile, but actually held a number of different types.
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. 5
The Receiver Variable in Frameworks u u 6 The greatest power of the receiver variable comes in the development of software frameworks. 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). Consider a class Window with subclasses Text. Window and Graphics. Window. The combination of foundation and deferred methods allow high level algorithms to be reused and specialized in new situations.
Example, Repainting Window u u u u u 7 class Window { public void repaint () { // invoke the deferred method paint. // Because the implicit receiver, this, // is polymorphic, the method from the // child class will be executed paint (graphics. Context); } abstract public void paint (Graphics g); // deferred private Graphics graphics. Context; } class Graphics. Window extends Window { public void paint (Graphics g) { // do the appropriate painting job } } Window w= new Graphics. Window(); w. repaint(); 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.
Self and Super u u u u 8 In Java and Smalltalk there is another pseudo-variable, named super. 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 Parent { void example. One () { System. out. println("In parent method"); } } class Child extends Parent { void example. One () { System. out. println("In child method"); super. example. One(); } }//Super. java Variable is called base in C#.
Downcast (Reverse Polymorphism) u u u u 9 It is sometimes necessary to undo the assignment to a polymorphic variable. That is, to determine the variables true dynamic value, and assign it to a variable of the appropriate type. This process is termed down casting, or, since it is undoing the polymorphic assignment, reverse polymorphism. Various different syntaxes are used for this, see the book. Parent a. Variable =. . . ; Child a. Card; if (a. Variable instanceof Child) a. Child = (Child) a. Variable;
Pure Polymorphism u u u u 10 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. class String. Buffer { String append (Object value) { return append(value. to. String()); }. . . }//Pure. Poly. java Note: this is a non-stop method! Different objects implement to. String differently, so the effects will vary depending upon the argument.
Another Example of Pure Polymorphism u u u u u 11 This example is from Smalltalk. between: low and: high ^ (low <= self) and: [ self <= high] Different arguments will implement the relational test differently, so different effects can be achieved. x between: $a and: $z x between: 1 and: 100 x between: 3. 14 and: 4. 56 x between: "abc" and: "pdq" x between: 10@5 and: 50@40
Summary of Polymorphic Variables u u u 12 A polymorphic Variable is a variable that can reference more than one type of object Polymorphic variables derive their power from interaction with inheritance, overriding and substitution. A common polymorphic variable is the implicit variable that maintains the receiver during the execution of a method Downcasting is the undoing of a polymorphic assignment Pure polymorphism occurs when a polymorphic variable is used as an argument.
Generics 13
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. 14
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. 15
C++ Templates u Function template u Class template 16
Function Template template <class T> return-type function-name(T param) u //one parameter function. u T is called template parameter. 17
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. 18
C++ Template Functions u u u u 19 The following illustrates a simple template function in C++, and its use. template <class T> T max(T left, T right) { if (left < right) return right; return left; } int a = max(3, 27); double d = max(3. 14, 2. 75); // see how types differ
u template u <class T> u void Display(const T &val) u { cout << val; } One parameter function with an additional parameters which are not template parameters u template <class T> u void Display(const T &val, ostream &os) u { os << val; } u The same parameter appear multiple times. u template 20 One parameter function template <class T> u void Swap(T & x, T &y) u {. . . }
Swap generic swap Function Template. . . Swap 2 integers 21 Swap 2 floats Swap 2 rationals . . .
Swap #include <iostream. h> template <class TParam> void Swap( TParam & x, TParam & y ) { TParam temp; temp = x; x = y; y = temp; } 22
Swap u class Student { u public: u Student( unsigned id = 0 ) u { u idnum = id; u } u int get. ID() {return idnum; }; u private: u unsigned idnum; u }; 23
Swap 24 int main() {int m = 10; int n = 20; Student S 1( 1234 ); Student S 2( 5678 ); cout << m<<" "<<n<<" "<<endl; Swap( m, n ); // call with integers cout << m<<" "<<n<<" "<<endl; cout << S 1. get. ID()<<" "<<S 2. get. ID()<<" "<<endl; Swap( S 1, S 2 ); // call with Students cout << S 1. get. ID()<<" "<<S 2. get. ID()<<" "<<endl; return 0; }//swap. cpp
Multiple parameter function template <class T 1, T 2> void Array. Input(T 1 array, T 2 & count) { for (T 2 j= 0; j < count; j++) {cout << “value: ”; cin >> array[j]; } } 25
Multiple parameter function template const unsigned temp. Count = 3; float temperature[temp. Count ]; const unsigned station. Count = 4; int station[station. Count ]; Array. Input(temperature, temp. Count); Array. Input(station, station. Count); 26
Example: Table Lookup #include <iostream. h> template <class T> long index. Of( T search. Val, const T * table, unsigned size ) { for( unsigned i=0; i < size; i++ ) if( search. Val == table[i] ) return i; return -1; } 27
Example: Table Lookup int main() { const unsigned i. Count = 10; const unsigned f. Count = 5; int i. Table[i. Count] = { 0, 10, 20, 30, 40, 50, 60, 70, 80, 90 }; float f. Table[f. Count] = { 1. 1, 2. 2, 3. 3, 4. 4, 5. 5 }; cout << index. Of( 20, i. Table, i. Count ) << endl; // "2" cout << index. Of( 2. 2 f, f. Table, f. Count ) << endl; // "1" const unsigned s. Count = 5; char * names[s. Count] = { "John", "Mary", "Sue", "Dan", "Bob" }; cout << index. Of( "Dan", names, s. Count )<<endl; // ? return 0; }//funtemplate. cpp 28
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. 29
Example: student class Student { public: Student( long id. Val ) { id = id. Val; } int operator ==( const Student & s 2 ) const { return id == s 2. id; } private: long id; // student ID number }; 30
Example: student int main() { const unsigned s. Count = 5; Student s. Table[s. Count] = { 10000, 11111, 20000, 22222, 30000 }; Student s( 22222 ); cout << index. Of( s, s. Table, s. Count )<<endl; // print "3" return 0; }//student. cpp 31
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. 32
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. 33
Class Template u Declare and define an object: template <class T> class My. Class{ //. . . } My. Class <int> x; My. Class <student> a. Student; 34
Template Classes u u u u u 35 While template functions are useful, it is more common to use templates with classes. template <class T> class Box { public: Box (T initial) : value(initial) { } T get. Value() { return value; } set. Value (T new. Value) { value = new. Value; } private: T value; };
Can Be Filled with Different Arguments Box <int> i. Box(7); i. Box. set. Value(3. 1415); u u u Box <double> d. Box(2. 7); cout << d. Box. get. Value(); d. Box. set. Value(3. 1415); cout << d. Box. get. Value(); i. Box = d. Box; u u u u In 36 // ERROR - invalid type //2. 7 //3. 1415 // ERROR - mismatched types the next chapter we will see how generics are used to create collection classes.
template <class T 1, class T 2> class Circle { //. . . private: T 1 x, y; T 2 radius; }; //. . . Circle <int, long> c 1; Circle <unsigned, float> c 2; 37 Simple Example
Class Template generic Array Class Template. . . integer Array 38 float Array FString Array . . .
Example: Array Class Template template <class T> class Array { public: Array( unsigned sz ); ~Array(); T & operator[]( unsigned i ); private: T * values; unsigned size; }; 39
Example: Array Class Template template<class T> Array<T>: : Array( unsigned sz ) { values = new T [sz]; size = sz; } template<class T> T & Array<T>: : operator[] ( unsigned i) { if( i >= size ) throw Range. Error(__FILE__, __LINE__, i); return values[i]; } template<class T> Array<T>: : ~Array() { delete [] values; } 40
Example: Array Class Template 41 int main() { const unsigned num. Dives = 2; Array<int> dive. Num( num. Dives ); Array<float> difficulty( num. Dives ); Array<FString> dive. Name (num. Dives); int j; for(j = 0; j < num. Dives; j++) {cout << "Enter dive #, difficulty level, dive name "; cin >> dive. Num[j] >> difficulty[j] >> ws; dive. Name[j]. Get. Line( cin ); } for(j = 0; j < 2; j++) cout << dive. Name[j] << 'n'; cout << endl; return 0; }//array. cpp, Fstring. h, range. h, array. h
Templates and Inheritances u Template u No is not a class inheritances for a template u. A class based on a template is an ordinary class u class t 1 : public Array u {. . . }//OK!!! templat <class T> u class Myclass: public Array u {//OK!!! u} u 42
Inheritance and Generics u u u u 43 Remember the class Box. Suppose a class Person has subclasses Boy. Child and Girl. Child. What is the relationship between Box<Person> and Box<Boy. Child>? Unfortunately, runs into problems with the principle of substitution. Assume Box<Boy. Child> is a subclass of Box<Person>, would make the following legal: Box<Person> a. Box = new Box<Boy. Child>; Person a. Girl = new Girl. Child; a. Box. set(a. Girl); A similar argument can be made for the reverse.
Inheritance and Arrays u Can make a similar argument for arrays: Boy. Child [ ] boys = new Boy. Child[10]; u Person [ ] people = boys; // copy or pointer semantics? u Girl. Child sally = new Girl. Child; 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! Other languages make the array assignment illegal. u u 44
Templates and static members u Keep in mind again: u Template u Static is not class, only template. members defined in a template are static members of the classes of this template. 45
Java Generics u List u Array. List u Linked. List u Vector http: //java. sun. com/j 2 se/1. 5/pdf/generics-tutorial. pdf 46
Java List u u 47 A List (sometimes called a sequence) is an ordered Collection that can contain duplicate elements. Like array indices, List indices are zero based (i. e. , the first element’s index is zero). 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 List. Iterator to access the elements. Interface List is implemented by several classes, including classes Array. List, Linked. List and Vector. http: //java. sun. com/j 2 se/1. 4. 2/docs/api/java/util/List. html
Array. List and Linked. List Class Array. List and Vector are resizable-array implementations of List. u Class Linked. List is a linked-list implementation of interface List. u Class Array. List’s behavior and capabilities are similar to those of class Vector. u The primary difference between Vector and Array. List is that objects of class Vector are synchronized by default, whereas objects of class Array. List are not. u //Collection. Test. java u //List. Test. java http: //java. sun. com/j 2 se/1. 5. 0/docs/api/java/util/Array. List. html u http: //java. sun. com/j 2 se/1. 4. 2/docs/api/java/util/Linked. List. html 48 http: //72. 5. 124. 55/j 2 se/1. 4. 2/docs/api/java/util/List. Iterator. html
List. Iterator u u 49 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. A List. Iterator 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(). In a list of length n, there are n+1 valid index values, from 0 to n, inclusive. 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(). http: //72. 5. 124. 55/j 2 se/1. 4. 2/docs/api/java/util/List. Iterator. html
Vector u u Like Array. List, class Vector provides the capabilities of array-like data structures that can resize themselves dynamically. Recall that class Array. List’s behavior and capabilities are similar to those of class Vector, except that Array. Lists do not provide synchronization by default. We cover class Vector here primarily because it is the superclass of class Stack. 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. //Vector. Test. java http: //java. sun. com/j 2 se/1. 4. 2/docs/api/java/util/Vector. html 50
Summary u Polymorphic u Self, variable super, this, base u Generics u Parameterized classes or functions u Template in C++ Function template u Class template u u Java Generics u List u Array. List u Linked. List u Vector 51
Can Even Be Used with User Defined Types u u u u 52 class Fraction { public: Fraction (int top, int bottom) { t = top; b = bottom; } int numerator() { return t; } int denominator() { return b; } bool operator < (Fraction & right) { return t * right. b < right. t * b; } private: int t, b; }; Fraction x(3, 4); Fraction y(7, 8); Fraction z = max(x, y); //fraction. cpp
- Slides: 52