Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "1 COSC2767: Object-Oriented Programming Haibin Zhu, Ph. D. Associate Professor of CS, Nipissing University."— Presentation transcript:

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

2 2 Lecture 5 Static, Dynamic Behavior and Substitution

3 3 Review or Refresh: C++ Pointers and Dynamic Allocation u Constant Pointers u Pointer Conversions u Allocating Memory

4 4 Constant Pointers u The object can not be modified when use this pointer to access. int n = 0; const int * cp = &n; * cp = 30;// Error! n = 30; //OK! //ex5-1.cpp

5 5 Constant Pointers u The same for parameters size_t strlen(const char * str) const char * aStr = “ABCDEFG”; char name [] = “Johnson”; unsigned n; n = strlen(aStr); n = strlen(name); u Can not pass a pointer to a constant to a function having a parameter that is a pointer to a non-constant

6 6 Example char * strcpy(char * dest, const char * source); … const char * des; const char * sou; strcpy(des, sou); //error!

7 7 Const-Qualified Pointers char message[80]; char *const sp = message; sp++; strcpy(sp, “A new message”); //error //OK

8 8 Const-Qualified Pointers char message[80]; const char *const sp = message; sp++; strcpy(sp, “A new message”); u //ex5-2.cpp //error

9 9 Four ways to declare a pointer char *p1 = message; char *const p2 = message; const char *p3 = message; const char *const p4 = message;

10 10 Functions returning Pointers to Constants u The variable receiving the returned value should be also a pointer to a constant. class Student{ public: const char * GetName() const; // … }

11 11 Functions returning Pointers to Constants Student s; char * ncName = S.GetName(); const char * cName = S.GetName(); //error //OK

12 12 What do the terms Static and Dynamic Mean? u In Programming languages: u Static almost always means fixed or bound at compile time, and cannot thereafter be changed. u Dynamic almost always means not fixed or bound until run time, and therefore can change during the course of execution.

13 13 Static and Dynamic Typing u In a statically typed programming language (C++, Java or Pascal), for example, variables have declared typed - - fixed at compile time. u In a dynamically typed programming language (Smalltalk or CLOS), a variable is just a name. Types are associated with values, not variables. A variable can hold different types during the course of execution.

14 14 Static Class and Dynamic Class u In a statically typed language we say the class of the declaration is the static class for the variable, while the class of the value it currently holds is the dynamic class. Most statically typed OO languages constrain the dynamic class to be a child class of the static class. u var u pet : Mammal; u fido : Dog u begin u pet := fido; // static class is Mammal, dynamic class is Dog u end;

15 15 Importance of Static Class u In a statically typed object-oriented language, the legality of a message is determined at compile time, based on the static class. u A message can produce a compile error, even if no run-time error could possibly arise: u class Mammal { } u class Dog extends Mammal { u void speak() { System.out.println("woof"); } u } u Mammal pet = new Dog; u pet.speak(); // will generate error, Mammals don't speak u //ex5-3.cpp, //Lect5 - java

16 16 Reverse Polymorphism u Polymorphism says we can assign a value from a child class to an instance of the parent class, but can this assignment then be reversed? Under what conditions? u var u pet : Mammal; u fido : Dog; u felice : Cat; u begin u pet := fido;// legal u fido := pet;// is this legal? u end; u This is known as the problem of reverse polymorphism.

17 17 Two aspects of reverse polymorphism u There are two specific problems associated with the question of reverse polymorphism. u The problem of identity - can I tell if a value declared as an instance of a parent class actually holds a value from a subclass. u The task of assignment - can I then assign the value from the parent class to a variable declared as the subclass. u In some languages mechanisms are provided to address these two problems together, while in other languages they are separated.

18 18 The Container Problem u The task of reverse polymorphism is often encountered in connection with a collection of values - we have a list of items from the parent class (say a list of Mammals), and when we extract a value we need to know if it is a more specific type. u Generally occurs in languages with a single inheritance tree, where the only type we may have associated with a value is the class ``Object''. u Solving this problem generally requires values to have ``self knowledge'' of their own type. In some languages they do, in some languages values do not.

19 19 Static and Dynamic Method Binding u Should the binding for information be associated with the static class of a variable or the dynamic class. u Alice holds a small Mammal - asks Bill ``does this animal give birth to live young''. u Static answer - All mammals give birth to live young - therefore yes. u What if the Mammal is a platypus? Dynamic answer - Platypus lay eggs, therefore no. u Even statically typed OOP languages can use dynamic binding. But may use static type to determine legality of operation.

20 20 Dynamic Method Binding u In many languages dynamic binding is the default (Java). u If a child class overrides a method in the parent, using the same type signature, then the selected method will be determined by the dynamic type. u In other languages (C++, Delphi, C#) the programmer must indicate which methods are dynamically bound and which are statically typed. u In C++ and C#, for example, this is done using the virtual keyword.

21 21 Merits of Static versus Dynamic Method Binding u Arguments concerning static versus dynamic binding mirror those concerning static versus dynamic typing. u Efficiency - static binding uses least CPU cycles, dynamic binding requires more time. u Error detection - static binding permits errors to be caught at compile time rather than run-time. u Flexibility - dynamic binding permits greater flexibility, static binding creates rigidity and inhibits reuse.

22 22 Constructors and Destructors- Static allocation class Student { private: int id; int credit; int GPA; char name[30]; public: Student (){ id = 0; credit = 0; GPA =0; strcpy(name, ""); cout<<"construct a student"<<endl; }; int getID() {return id;} int getCredit() {return credit;} int getGPA() {return GPA;} void setID(int anID) {id=anID;} void setCredit(int aCredit) {credit=aCredit;} void setGPA(int aGPA) {GPA=aGPA;} char * getName() {return name;} void setName(char *nm) {strcpy(name,nm);} ~Student() { cout<<"delete a student."<<endl;}; };//ex5-4.cpp

23 23 Constructors and Destructors- Dynamic allocation class Student { private: int id; int credit; int GPA; char *name; public: Student (){ id = 0; credit = 0; GPA =0; name = new char [30]; strcpy(name, "no name"); cout<<"construct a student"<<endl; }; int getID() {return id;} int getCredit() {return credit;} int getGPA() {return GPA;} void setID(int anID) {id=anID;} void setCredit(int aCredit) {credit=aCredit;} void setGPA(int aGPA) {GPA=aGPA;} char * getName() {return name;} void setName(char *nm) {strcpy(name,nm);} ~Student() {delete name; cout<<"delete a student."<<endl;}; };//ex5-5.cpp

24 24 Idealization of is-a Relationship u A TextWindow is-a Window u Because TextWindow is subclassed from Window, all behavior associated with Windows is also manifest by instances of TextWindow. u Therefore, a variable declared as maintaining an instance of Window should be able to hold a value of type TextWindow. u Unfortunately, practical programming language implementation issues complicate this idealized picture.

25 25 Memory Allocation - Stack and Heap Based u Generally, programming languages use two different techniques for allocation of memory. u Stack-based allocation. Amount of space required is determined at compile time, based on static types of variables. Memory allocation and release is tied to procedure entry/exit. Can be performed very efficiently. u Heap-based allocation. Amount of space used can be determined at run-time, based upon dynamic considerations. Memory allocation and release is not tied to procedure entry/exit, and either must be handled by user or by a run-time library (garbage collection). Generally considered to be somewhat less efficient.

26 26 The Problem with Substitution u class Window { u public: u virtual void oops(); u private: u int height; u int width; u }; u class TextWindow : public Window { u public: u virtual void oops(); u private: u char * contents; u int cursorLocation; u }; u main() u {Window x; // how much space to set aside? u TextWindow y; u x = y; // what should happen here? u }

27 27 Memory Strategies u How much memory should be set aside for the variable x ? u 1. (Minimum Static Space Allocation) Allocate the amount of space necessary for the base class only. (C++) u 2. (Maximum Static Space Allocation) Allocate the amount of space for the largest subclass. u 3. (Dynamic Space Allocation) Allocate for x only the amount of space required to hold a pointer. (Smalltalk, Java)

28 28 Minimum Static Space Allocation u The language C++ uses the minimum static space allocation approach. u This is very efficient, but leads to some subtle difficulties. u What happens in the following assignment? u Window x; u TextWindow y; u x = y; //???

29 29 Assigning a Larger Value to a Smaller Box

30 30 The Slicing Problem u The problem is you are trying to take a large box and squeeze it into a small space. Clearly this won't work. Thus, the extra fields are simply sliced off. u Question - Does this matter? u Answer - Only if somebody notices. u Solution - Design the language to make it difficult to notice.

31 31 Rules for Member Function Binding in C++ u The rules for deciding what member function to execute are complicated because of the slicing problem. u 1. With variables that are declared normally, the binding of member function name to function body is based on the static type of the argument (regardless whether the function is declared virtual or not). u 2. With variables that are declared as references or pointers, the binding of the member function name to function body is based on the dynamic type if the function is declared as virtual, and the static type if not.

32 32 C10 o10; … p=&o10; p->f1() C1 o1 C10 o10; … o1=o10; o1.f1(); NO Polymorphism! YES Polymorphism! Ex5-6.cpp

33 33 Examples in C++ u class Animal { u public: u virtual void speak () { cout << "Animal Speak !\n"; } u void reply () { cout << "Animal Reply !\n"; } u }; u class Dog : public Animal { u public: u virtual void speak () { cout << "woof !\n"; } u void reply () { cout << "woof again!\n"; } u }; u class Bird : public Animal { u public: u virtual void speak () { cout << "tweet !\n"; } u }; u Ex5-7.cpp Animal a; Dog b; b.speak();//woof ! a = b; a.speak();//woof? Bird c; c.speak();//tweet ! a = c; a.speak();//tweet ?

34 34 Maximum Static Space Allocation u A different approach would be to allocate the Maximum amount of space you would ever need. u Would nicely solve the slicing problem. u Would often allocate unused space. u Maximum amount of space not known until all classes have been seen. u For this reason, not used in practice.

35 35 Dynamic Memory Allocation u In the third approach, all objects are actually pointers. u Only enough space for a pointer is allocated at compile time. u Actual data storage is allocated on the heap at run- time. u Used in Smalltalk, Object Pascal, and Objective-C, Java. u Requires user to explicitly allocate new objects and, in some languages, explicitly free no longer used storage. u May also lead to pointer semantics for assignment and equality testing.

36 36 Meaning of Assignment? u What does it mean when an instance of a class is assigned to another variable? u class Box { u public int value; u } u Box x = new Box(); u x.value = 7; u Box y = x; u y.value = 12; // what is x.value? u Two possibilities: u Copy semantics. x and y are independent of each other, a change in one has no effect on the other. u Pointer semantics. x and y refer to the same object, and hence a change in one will alter the other.

37 37 Copy Semantics versus Pointer Semantics u If a value is indirectly accessed through a pointer, when an assignment is performed (or equality test is made) is the quantity assigned simply the pointer or is it the actual value?

38 38 Problems with Pointer Semantics u If x is assigned to y and then changes are made to x, are these changes reflected in y? u If x is explicitly freed, what happens if the user tries to access memory through y? u In C++, programmer can make assignment (equality testing) mean anything they want. u Object Pascal, Java uses pointer semantics, no built-in provision for copies. u Smalltalk and Objective-C use pointer semantics, have several techniques for making copies.

39 39 An Old Story Concerning Equality A man walks into a pizza parlor and sits down. A waiter comes to the table and asks the man what he would like to order. The man looks around the room, then points to the woman sitting at the next table, and says ``I'll have what she is eating.'' The waiter thereupon walks to the woman’s table, picks up the half-eaten pizza from in front of her, and places it before the startled customer. u A classic confusion between equality and identity.

40 40 Equality and Identity u A test for identity asks whether two variables refer to exactly the same object. u A test for equality asks whether two variables refer to values that are equivalent. u Of course, the meaning of equivalent is inherently domain specific. Object-oriented languages allow the programmer to control the meaning of the equality test by allowing the redefinition of a standard method. (For example, equals in Java).

41 41 Paradoxes of Equality, Part 1 u But child classes cannot change the type signature of overridden methods. This means the argument must often be more general than one would like: u class Object { u public boolean equals (Object right) { u... u } u class PlayingCard extends Object { u public boolean equals (Object right) { u... // right must be object even if we are only u... // interested in comparing cards to cards u }

42 42 Paradoxes of Equality, Part 2 u Because equality is a message sent to the left argument, there is no guarantee that properties such as symmetry or transitivity are preserved: u class Foo { u boolean equals (Object right) {... } u } u Foo a, b; u if (a.equals(b)) // even if this is true u if (b.equals(a)) // no guarantee that this is true

43 43 Paradoxes of Equality, Part 3 u And if you add inheritance into the mix, the possibilities for paradoxical behavior increase even more. u class Parent { u boolean equals (Object x) {... } u } u class Child extends Parent { u boolean equals (Object x) {... } u } u Parent p; u Child c; u if (p.equals(c)) // will execute using the parent method u if (c.equals(p)) // will execute using the childs method

44 44 References in Java C++Java Pair origin;Pair origin = new Pair(); Pair *p, *q, *r;Pair p, q, r; origin.x = 0; p = new Pair;p = new Pair(); p -> y = 5;p.y = 5; q = p; r = &origin; not possible

45 45 Pass ``by value'‘ in Java u void f() { u int n = 1; u Pair p = new Pair(); u p.x = 2; p.y = 3; u System.out.println(n); // prints 1 u System.out.println(p.x); // prints 2 u g(n,p); u System.out.println(n); // still prints 1 u System.out.println(p.x); // prints 100 u } u void g(int num, Pair ptr) { u System.out.println(num); // prints 1 u num = 17; // changes only the local copy u System.out.println(num); // prints 17 u System.out.println(ptr.x);// prints 2 u ptr.x = 100; // changes the x field of caller's Pair u ptr = null; // changes only the local ptr u }//FunctionCalls.java

46 46 Array in Java int x = 3; // a value int[] a; // a pointer to an array object; initially null int a[]; // exactly the same thing a = new int[10]; // now a points to an array object a[3] = 17; // accesses one of the slots in the array a = new int[5]; // assigns a different array to a // the old array is inaccessible (and so // is garbage-collected) int[] b = a; // a and b share the same array object System.out.println(a.length); // prints 5 //Array.java

47 47 String in Java (1) u String s = "hello"; u String t = "world"; u System.out.println(s + ", " + t); // prints "hello, world" u System.out.println(s + "1234"); // "hello1234" u System.out.println(s + (12*100 + 34)); // "hello1234" u System.out.println(s + 12*100 + 34); // "hello120034" (why?) u System.out.println("The value of x is " + x); // will work for any x u System.out.println("System.out = " + System.out); u // "System.out = java.io.PrintStream@80455198" u String numbers = ""; u for (int i=0; i<5; i++) u numbers += " " + i; u System.out.println(numbers); // " 0 1 2 3 4"

48 48 String in Java (2) String s = "whatever", t = "whatnow"; s.charAt(0); // 'w' s.charAt(3); // 't' t.substring(4); // "now" (positions 4 through the end) t.substring(4,6); // "no" (positions 4 and 5, but not 6) s.substring(0,4); // "what" (positions 0 through 3) t.substring(0,4); // "what" s.compareTo(t); // a value less than zero; s precedes t in "lexicographic" // (dictionary) order t.compareTo(s); // a value greater than zero (t follows s) t.compareTo("whatnow"); // zero t.substring(0,4) == s.substring(0,4);// false (they are different String objects) t.substring(0,4).equals(s.substring(0,4));// true (they are both equal to "what") t.indexOf('w'); // 0 t.indexOf('t'); // 3 t.indexOf("now"); // 4 t.lastIndexOf('w'); // 6 t.endsWith("now"); // true //TestString.java

49 49 Binding in Java(1) class Animal { public void speak () { System.out.println("Animal Speak !\n"); } void reply () { System.out.println("Animal Reply !\n"); } }; class Dog extends Animal { public void speak () { System.out.println("woof!\n"); } void reply () { System.out.println("woof again!\n"); } }; class Bird extends Animal { public void speak () { System.out.println("tweet !"); } }; public class Binding { public static void main(String[] arg) { Animal a=new Animal(); Dog b=new Dog(); b.speak();//woof ! a = b; a.speak();//woof ! Bird c=new Bird(); c.speak();//tweet ! a = c; a.speak();//tweet ! } }//binding.java

50 50 Binding in Java (2) class Window { publicvoid oops() {System.out.println("Window oops\n"); }; privateint height, width; }; class TextWindow extends Window { public void oops() {System.out.println("TextWindow oops\n"); }; privateString contents; privateint cursorLocation; }; public class windows { public static void main(String[] arg) { TextWindow x=new TextWindow(); Window a=new Window(); Window b; TextWindow c; a.oops(); a = x; a.oops(); b = x; b.oops(); c = x; c.oops(); } }//windows.java //Project: WindowCalssesForBinding

51 51 Binding in Java(3) u Dynamic binding u All declarations are references. u Function calls are “call-by-value” and “call-by-reference”.

52 52 Summary u C++ Pointers u Static and Dynamic Behavior u Static and Dynamic Method Binding u Memory Strategies u Copy u Equality and Identity u All the above properties in Java


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

Similar presentations


Ads by Google