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

Slides:



Advertisements
Similar presentations
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.
Advertisements

Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
Lecture 10: Part 1: OO Issues CS 540 George Mason University.
Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
Exception Handling The purpose of exception handling is to permit the program to catch and handle errors rather than letting the error occur and suffer.
1 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
Chapter 1 OO using C++. Abstract Data Types Before we begin we should know how to accomplish the goal of the program We should know all the input and.
UMBC 1 Static and Dynamic Behavior CMSC 432 Shon Vick.
Inheritance. In this chapter, we will cover: The concept of inheritance Extending classes Overriding superclass methods Working with superclasses that.
1 Chapter 7 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
Introduction to Data Structures, Spring 2007 Slide- 1 California State University, Fresno Introduction to Data Structure Object Oriented Programming Concepts.
Static and Dynamic Behavior Fall 2005 OOPD John Anthony.
OOP Spring 2006 – Recitation 31 Object Oriented Programming Spring 2006 Recitation 3.
Inheritance, Polymorphism, and Virtual Functions
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Shallow Versus Deep Copy and Pointers Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data.
CSCI-383 Object-Oriented Programming & Design Lecture 15.
Programming Languages and Paradigms Object-Oriented Programming.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Polymorphism. Introduction ‘one name multiple forms’ Implemented using overloaded functions and operators Early binding or static binding or static linking.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide
OOPs Object oriented programming. Based on ADT principles  Representation of type and operations in a single unit  Available for other units to create.
Presented by: Mojtaba Khezrian. Agenda Object Creation Object Storage More on Arrays Parameter Passing For Each VarArgs Spring 2014Sharif University of.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Static and Dynamic Behavior CMPS Power of OOP Derives from the ability of objects to change their behavior dynamically at run time. Static – refers.
1 Chapter 10: Data Abstraction and Object Orientation Aaron Bloomfield CS 415 Fall 2005.
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.
Unit IV Unit IV: Virtual functions concepts, Abstracts classes & pure virtual functions. Virtual base classes, Friend functions, Static functions, Assignment.
OOP and Dynamic Method Binding Chapter 9. Object Oriented Programming Skipping most of this chapter Focus on 9.4, Dynamic method binding – Polymorphism.
CSCI 383 Object-Oriented Programming & Design Lecture 17 Martin van Bommel.
CSSE501 Object-Oriented Development. Chapter 11: Static and Dynamic Behavior  In this chapter we will examine the differences between static and dynamic.
More on Hierarchies 1. When an object of a subclass is instantiated, is memory allocated for only the data members of the subclass or also for the members.
Parameters… Classes Cont Mrs. C. Furman October 13, 2008.
Peyman Dodangeh Sharif University of Technology Fall 2013.
Inheritance, Polymorphism, And Virtual Functions Chapter 15.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
What Is Inheritance? Provides a way to create a new class from an existing class New class can replace or extend functionality of existing class Can be.
Sadegh Aliakbary Sharif University of Technology Spring 2011.
 Objects versus Class  Three main concepts of OOP ◦ Encapsulation ◦ Inheritance ◦ Polymorphism  Method ◦ Parameterized ◦ Value-Returning.
OOP using C Abstract data types How to accomplish the task??? Requirements Details Input, output, process Specify each task in terms of input.
(1) ICS 313: Programming Language Theory Chapter 12: Object Oriented Programming.
OOPs Object oriented programming. Abstract data types  Representationof type and operations in a single unit  Available for other units to create variables.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
CSC241 Object-Oriented Programming (OOP) Lecture No. 5.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Peyman Dodangeh Sharif University of Technology Spring 2014.
Peyman Dodangeh Sharif University of Technology Fall 2014.
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.
Java & C++ Comparisons How important are classes and objects?? What mechanisms exist for input and output?? Are references and pointers the same thing??
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Polymorphism and Virtual Functions One name many shapes behaviour Unit - 07.
Lecture 12 Implementation Issues with Polymorphism.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
CSCI-383 Object-Oriented Programming & Design Lecture 17.
CSCI 383 Object-Oriented Programming & Design Lecture 15 Martin van Bommel.
Design issues for Object-Oriented Languages
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Modern Programming Tools And Techniques-I
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Inheritance, Polymorphism, and Virtual Functions
ATS Application Programming: Java Programming
Inheritance Basics Programming with Inheritance
Inheritance, Polymorphism, and Virtual Functions
Computer Programming with JAVA
Advanced Programming in Java
SPL – PS3 C++ Classes.
Static Binding Static binding chooses the function in the class of the base class pointer, ignoring any versions in the class of the object actually.
Presentation transcript:

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

2 Lecture 5 Static, Dynamic Behavior and Substitution

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

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 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 Example char * strcpy(char * dest, const char * source); … const char * des; const char * sou; strcpy(des, sou); //error!

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

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

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

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 Functions returning Pointers to Constants Student s; char * ncName = S.GetName(); const char * cName = S.GetName(); //error //OK

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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 Assigning a Larger Value to a Smaller Box

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 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 C10 o10; … p=&o10; p->f1() C1 o1 C10 o10; … o1=o10; o1.f1(); NO Polymorphism! YES Polymorphism! Ex5-6.cpp

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 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 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 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 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 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 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 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 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 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 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 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 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 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 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* )); // "hello1234" u System.out.println(s + 12* ); // "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 = u String numbers = ""; u for (int i=0; i<5; i++) u numbers += " " + i; u System.out.println(numbers); // " "

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 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 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 Binding in Java(3) u Dynamic binding u All declarations are references. u Function calls are “call-by-value” and “call-by-reference”.

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