ReviewSlides CMPS 2143. 2 Advantages/Disadvantages Statically typed languages ▫ Type checking can be done at compile time ▫ Memory layout can be determined.

Slides:



Advertisements
Similar presentations
Containers CMPS Reusable containers Simple data structures in almost all nontrivial programs Examples: vectors, linked lists, stacks, queues, binary.
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.
1 COSC2767: Object-Oriented Programming Haibin Zhu, Ph. D. Associate Professor of CS, Nipissing University.
Design Patterns CMPS Design Patterns Consider previous solutions to problems similar to any new problem ▫ must have some characteristics in common.
C12, Polymorphism “many forms” (greek: poly = many, morphos = form)
Overloading CMPS Overloading A term is overloaded if it has many different meanings ▫ many English words are : eg. blue In programming languages,
UMBC 1 Static and Dynamic Behavior CMSC 432 Shon Vick.
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.
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
Subclasses and Subtypes CMPS Subclasses and Subtypes A class is a subclass if it has been built using inheritance. ▫ It says nothing about the meaning.
OOP Languages: Java vs C++
Engr 691 Special Topics in Engineering Science Software Architecture Spring Semester 2004 Lecture Notes.
Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
Pointer Data Type and Pointer Variables
Learners Support Publications Pointers, Virtual Functions and Polymorphism.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Static and Dynamic Behavior CMPS Power of OOP Derives from the ability of objects to change their behavior dynamically at run time. Static – refers.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Programming Languages and Paradigms Object-Oriented Programming (Part II)
Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.
1 COSC3557: Object-Oriented Programming Haibin Zhu, Ph. D. Associate Professor of CS, Nipissing University.
CSSE501 Object-Oriented Development. Chapter 12: Implications of Substitution  In this chapter we will investigate some of the implications of the principle.
Object Interconnections CMPS Object Interconnections Past few chapters: focused on individual classes in isolation or classes in parent/child relationships.
CSCI-383 Object-Oriented Programming & Design Lecture 13.
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.
CSCI 383 Object-Oriented Programming & Design Lecture 17 Martin van Bommel.
OOP Class Lawrence D’Antonio Lecture 3 An Overview of C++
CSSE501 Object-Oriented Development. Chapter 11: Static and Dynamic Behavior  In this chapter we will examine the differences between static and dynamic.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
Learners Support Publications Classes and Objects.
Data Structures Using C++ 2E1 Inheritance An “is-a” relationship –Example: “every employee is a person” Allows new class creation from existing classes.
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Session 24 Chapter 12: Polymorphism. Polymorphism polymorphism comes from the Greek root for “many forms” polymorphism is about how we can use different.
 Objects versus Class  Three main concepts of OOP ◦ Encapsulation ◦ Inheritance ◦ Polymorphism  Method ◦ Parameterized ◦ Value-Returning.
Polymorphism CMPS Poly-morphism Means “many-forms” Means different things in biology, chemistry, computer science Means different things to functional.
Interfaces F What is an Interface? F Creating an Interface F Implementing an Interface F What is Marker Interface?
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
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.
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.
Chapter 4: More Object Concepts. Objectives Understand blocks and scope Overload a method Avoid ambiguity Create and call constructors with parameters.
 Static  Example for Static Field  Example for Static Method  Math class methods  Casting  Scope of Declaration  Method Overloading  Constructor.
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.
Lecture 12 Implementation Issues with Polymorphism.
Internet Computing Module II. Syllabus Creating & Using classes in Java – Methods and Classes – Inheritance – Super Class – Method Overriding – Packages.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
CSCI-383 Object-Oriented Programming & Design Lecture 17.
9.1 CLASS (STATIC) VARIABLES AND METHODS Defining classes is only one aspect of object-oriented programming. The real power of object-oriented programming.
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.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Template Classes CMPS 2143.
7. Inheritance and Polymorphism
Java Primer 1: Types, Classes and Operators
Inheritance and Run time Polymorphism
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
Classes and Objects.
CISC/CMPE320 - Prof. McLeod
Java Programming Language
Presentation transcript:

ReviewSlides CMPS 2143

2

Advantages/Disadvantages Statically typed languages ▫ Type checking can be done at compile time ▫ Memory layout can be determined at compile time for automatic variables ▫ EFFICIENT Dynamically typed languages ▫ FLEXIBILITY ▫ Example: 3 function max (left, right) { if (left < right) return right; return left; }

Static versus Dynamic Method Binding In OOP languages, the binding of a method to execute in response to a message is determined by the dynamic value of the receiver. 4

C++ 5 class Animal { public: virtual void speak() {cout << “Animal Speak !”;} }; class Dog : Animal { public: virtual void speak() {cout << “Woof !”;} }; Animal pet; //automatic memory allocation!!! Dog d; d.speak(); //Woof ! pet = d; pet.speak(); //Animal Speak !

C++ 6 class Animal { public: virtual void speak() {cout << “Animal Speak !”;} }; class Dog : Animal { public: virtual void speak() {cout << “Woof !”;} }; Animal * pet; //dynamic memory allocation!!! Dog * d = new Dog(); D->speak(); //Woof ! pet = d; pet->speak(); //Woof!

7

Space Allocation 1.Minimum space allocation: Allocate the amount of space necessary for the base class. 2.Maximum space allocation: Allocate the amount of space necessary to hold the maximum size of any legal value (from any of the classes in the hierarchy) 3.Dynamic memory allocation: Allocate only the amount of space necessary to hold a single pointer/reference. (Allocate the space necessary for the value at runtime on the heap.) 8

Minimum Space Allocation Default: not all fields copied/only the corresponding fields. (termed slicing) 9

Dynamic Memory Allocation Values of objects not stored on the stack – only the pointer or reference is Values stored in the heap. Java, Smalltalk, Object Pascal, Objective-C use this approach Must use new to allocate space in the heap. 10

Assignment – 2 interpretations Copy semantics – assignment copies entire value of right side, assigning it to left, thereafter the two values are independent (changes in one not reflected in other) ▫ Sometimes used in C++, sometimes not Pointer semantics – Assignment changes the reference of left side to be of right side (aliasing). Two pointers refer to the same memory location. (Changes in one, will affect the other.) ▫ Java, CLOS, Object Pascal ▫ If used, languages usually provide a means for true copy 11

Copies and Clones How to copy a value that references other objects? Shallow copy ▫ assignment of references Deep copy ▫ Overload assignment ▫ Write copy constructor ▫ Overload clone method 12

13

Multiple Inheritance of Interfaces C++ and Smalltalk allow multiple inheritance of classes Java and C# do not ▫ Fake it with multiple inheritance of interfaces ▫ REUSE concept, not code! 14

15

Four forms of polymorphism Overloading – ad hoc polymorphism Overriding – inclusion polymorphism Polymorphic variables – assignment polymorphism ▫ or if used as an argument to a method/function – pure polymorphism Generics (templates) Downcasting – reverse polymorphism 16

Overloading AKA ad-hoc polymorphism Single function/method name has several alternative implementations Distinguished at compile time by type signature class myClass { public: //3 overloaded meanings for same name void example (int x) {…} void example (int x, double y) {…} void example (string x) {…} } 17

Overriding Single function/method name has several alternative implementations with the same signature, but occurs within context of the parent class/child class relationship class Parent { public: void example (int x) {…} } class Child { public: //same name, different method body void example (int x) {…} } 18

Polymorphic Variable also known as assignment polymorphism Variable is declared of one type, but holds a value of a different type //declared as parent, holding child value Room r = new King(…); When a polymorphic variable is used as an argument, the result function/method is said to exhibit pure polymorphism. 19

Generics/Templates – More in Chapter 18 A way of creating general purpose tools and specializing them to specific situations template T max (T left, T right){ if (left < right) return right; return left; } A generic function or class is parameterized by type ▫ Similar to the way a function is parameterized by values The type is unspecified, to be filled in later 20

21

OPERATOR OVERLOADING Some languages allow operator overloading ▫ Java does not Giving the normal C++ operators such as +, -, *, <=, and += etc., additional meanings when they are applied to user-defined types (classes) You cannot create new operators like *& and try to overload them; only existing operators can be overloaded

OVERLOADING BINARY OPERATORS class StringExt : public Object { public: //constructors StringExt(); StringExt (string s); StringExt (const StringExt & other); //overloaded + for concatenation StringExt operator + (StringExt se); StringExt operator + (int i); StringExt operator + (double r); StringExt operator + (string s); //overloaded = for assignment void operator = (string s); void operator = (StringExt se); //returns the string equivalent of the StringExt virtual string toString (); private: string val; };

Resolving Overloaded Calls Example: void order (Dessert d, Cake c); void order (Pie p, Dessert d); void order (ApplePie a, Cake c); order (aDessert, aCake); //legal;exact- 1 order (anApplePie, aDessert); //legal - 2 order (aDessert, aDessert); //illegal //all eliminated in step 1, can’t downcast order (anApplePie, aChocolateCake); //legal //all in set; 1,2 eliminated in step2, //because 3’s parameters more specific order (aPie, aCake); //illegal //3 elim. in step 1, but 2 and 3 survive step 2

Conversion C++ gives programmer control over how an instance of a class can be implicitly converted to another type ▫ use a constructor with a single argument ▫ rule to compiler to convert arg type to class type class ComplexNumber { public: ComplexNumber(); ComplexNumber(double r, double i); ComplexNumber (double r); : } ComplexNumber::ComplexNumber (double r) { real = r; imag = 0; }

ComplexNumber c(4.5,3.2); ComplexNumber result; double r = 5; result = c + r; //r will be converted to a //ComplexNumber and ComplexNumber + //will be performed

27

Overriding Recall, a method in a child class overrides a method in the parent class, if it has the same name and type signature. Also known as inclusion polymorphism ▫ important when combined with substitution 28 Parent void method (int, float Child void method (int, float AnotherChild …

Overriding vs Overloading OverloadingOverriding same method name two or more method bodies classes that methods appear in do NOT have to be in parent/child relationship signatures MUST NOT match methods are SEPARATE resolved at COMPILE-TIME same method name two or more method bodies classes that methods appear in MUST be in parent/child relationship signatures MUST match methods SOMETIMES COMBINED resolved at RUN-TIME 29

Replacement vs Refinement There are actually two different ways that overriding can be handled : ▫ A replacement totally and completely replaces the code in the parent class the code in the child class. ▫ A refinement executes the code in the parent class, and adds to it the code in the child class. Constructors, for example, almost always use refinement. 30

Replacement Two major reasons for using replacement ▫ the method is the parent class is abstract (or pure virtual), it MUST be replaced ▫ the method in the parent class is a default method, not appropriate for all situations  recall Animal speak() method, and Dog speak method() earlier ▫ the child method is more efficient than the parent method  parent class polygon and child class square with methods computeArea(); 31

Refinement Code in child class combined with code in parent class and both executed ▫ constructors perform a refinement ▫ in most languages, code from parent class executed first 32

Refinement C++ example void Parent:: example(int a) { cout << “in parent code\n”; } void Child::example(int a) { Parent::example(12); //do parent action cout << “in child code\n”; } Java example class Parent { public void example(int a) {cout << “in parent code\n”;} } class Child { public void example(int a) { super.example(12); //do parent action cout << “in child code\n”; } 33

Overriding versus Shadowing It is common in programming languages for one declaration of a variable to shadow a previous variable of the same name Shadowing is resolved at compile time class Silly { private int x; // an instance variable named x public void example (int x) { // x shadows instance variable int a = x+1; while (a > 3) { int x = 1; //local variable shadows parameter a = a - x; }

Shadowing Methods Many of those languages that require the virtual keyword in the parent class will use shadowing if it is omitted: class Parent { public: // note, no virtual keyword here void example () { cout << "Parent" << endl; } }; class Child : public Parent { public: void example () { cout << "Child" << endl; } }; Parent * p = new Parent(); p->example(); //Parent Child * c = new Child(); c->example(); //Child p = c; // be careful here! p->example(); // Parent

Overriding, Shadowing and Redefinition Overriding ▫ The type signatures are the same in both parent and child classes, and the method is declared as virtual in the parent class. Shadowing ▫ The type signatures are the same in both parent and child classes, but the method was not declared as virtual in the parent class. Redefinition ▫ The type signature in the child class differs from that given in the parent class.  (Example available in Chapter 15)

The Polymorphic Variable A polymorphic variable is a variable that can reference more than one type of object (that is, it can hold values of different types during the course of execution). Example public class Shape{ } public Shape shapes[ ]; public void drawAll(Shape [] shapes) { for (int i = 0; i < numShapes; i++) shapes[i].drawSelf(); } The variable was declared as Shape, but actually held a number of different types.

Downcast (Reverse Polymorpism) 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.

Downcast (Reverse Polymorpism) Examples in Java and C++: Parent aVariable =...; Child aChild; if (aVariable instanceof Child) aChild = (Child) aVariable ; Parent * aVariable = new...; Child * aChild = dynamic_cast (aVariable); if (aChild != 0) {//null if not legal, nonnull if ok. : }

Pure Polymorphism 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 values. Different objects implement toString differently, so the effects will vary depending upon the argument. class StringBuffer { String append (Object value) { return append(value.toString()); }... }

41

Another form of polymorphism Generics (or templates) in C++ provide a way to parameterize a function or a class by use of a type A name is defined as a type parameter in the case of a class, eg. List list; Then that type is used within the class definition in place of the parameter Generics in C++, Eiffel, ML, Haskell, Ada, and Java 7

The template class declaration template class NewClass { public: NewClass (); NewClass (T initialData); NewClass (NewClass other); void setData (const T & newValue); T getData () const; void resize (int newSize); NewClass operator + (const NewClass & newClass1, const NewClass & newClass2) private: T theData; } ; #include “NewClass.cpp”

template T NewClass::setData(const T & newValue ) { theData = T; //assumes = is defined for T } template NewClass NewClass ::operator + (const NewClass & newClass1, const NewClass & newClass2) { NewClass result; result = ??? return result; } Methods

Ex2. Instead non-member function looks like NewClass nmFunction(const NewClass & newClass1, const NewClass & newClass2) {... } template NewClass nmFunction (const NewClass & newClass1, const NewClass & newClass2) { … }

NOTE: The name NewClass is changed to NewClass only when it is used as a class name void main() { NewClass myFirst; NewClass mySecond (2); NewClass myThird (33); NewClass myFourth (4.5); myFirst.setData (5); cout << myFourth.getData() << endl; myFirst = nmFunction (mySecond, myThird);. :

47

Reusable containers Simple data structures in almost all nontrivial programs Examples: vectors, linked lists, stacks, queues, binary trees, sets, dictionaries, etc. So common  expect ideal for development as reusable components

inheritance as mechanism for specialization (Set and Bag) deferred methods (add and remove in Collection) inheritance as mechanism for construction (Dictionary)

composition (Bag has a dictionary) ▫ key is the element in the bag ▫ value is the number of times element is in the bag

Element traversal on Containers Provides method that allow you to loop over the elements in the container bool hasMoreElements(); //return true iff there are more elements to process ItemType nextElement(); //return next element void reset(); //start at first element

Visual Studio STL containers us/library/1fe2x6kt(v=vs.110).aspx us/library/1fe2x6kt(v=vs.110).aspx

53

Coupling and Cohesion Good modular design that requires ▫ Low coupling ▫ High cohesion Coupling – describes the relationships between classes Cohesion – describes the relationships of the members within a class Well-designed classes ▫ Should have a purpose ▫ All elements should be associated with a single task

Varieties of Coupling (Worst to Best) Internal Data Coupling ▫ Instances of one class can directly modify instance variables in an instance of another class Global Data Coupling ▫ Two or more classes rely on some common global data structure ▫ Solution – create another class to hold and manage this data BOTH of these BAD – because it complicates ability to understand class in isolation

Varieties of Coupling (Worst to Best) Control (or Sequence) Coupling ▫ An instance of one class must perform operations in a fixed order, but that order is controlled elsewhere ▫ When unavoidable, object assures ops performed in correct order Component Coupling ▫ An instance on a class has-a member data field that is an instance of another class ▫ Ideally the relationship should be only one way ▫ Examples: Set used a List and Bag used a Dictionary

Varieties of Coupling (Worst to Best) Parameter Coupling ▫ An instance of one class must invoke services (methods) from another and the only relationships are the number and type of parameters supplied and the type returned ▫ Common, easy to see, easy to verify statically ▫ Example: void List::insertInOrder (String s);  Will have to call String equals method Subclass Coupling ▫ Particular to OOP ▫ Relationship a class has with its parent class

Varieties of Cohesion (Weakest to Best) Coincidental ▫ When elements of a class are grouped for no apparent reason ▫ Often result of “modularizing” a large program arbitrarily Logical ▫ When there is a logical connection among elements, but no actual connection in either data or control ▫ Example: Math class

Varieties of Cohesion (Worst to Best) Temporal ▫ When elements are bound together because they all must be used at approximately the same time  Example: program initialization or finalization Communicational ▫ When methods in a class are grouped because they all access the same I/O data or devices ▫ Class acts as a “manager” of the data or device

Varieties of Cohesion (Worst to Best) Sequential ▫ When elements in a class are linked by the necessity to be activated in a particular order ▫ Usually the result of avoiding sequential coupling Functional ▫ Desirable type of binding of elements when they all relate to the performance of a single function Data ▫ Class defines a set of data values and makes public methods that manipulate the data abstraction

Give-a-ways for estimate degree of coupling Purpose statement of class is a compound sentence ▫ Containing commas or more than one verb ▫ Probably sequential or communicational coupling Purpose statement of class refers to time ▫ First, next, then, after, when, start ▫ Probably sequential or temporal coupling Purpose statement does not contain a single, specific object following a verb ▫ Edit all data  logical binding ▫ Edit source data  functional binding Purpose statement contains words initialize, clean-up ▫ Probably temporal binding

Friendship Another aspect of visibility in C++ is concept of a friend function. Friends of a class are not members of the class, yet can access the non-public members of the class A class can have two types of friends ▫ Friend functions ▫ Friend classes

Friend Functions To declare a function as friend of a class, precede the function prototype in the class definition with keyword friend. Member access notions of private, public etc. are not relevant to friend declaration, so friend declarations can be placed anywhere in a class definition. As a good programming practice, place all friendship declarations first inside the class definition’s body and do not precede them with any access specifier

Friend Function Example class Count { friend void setX(Count & c, int val); public: Count(): x(0) {} void print() const{cout<<x<<endl;} private: int x; };

Friend Function Example void setX(Count & c, int val){ c.x=val;} void main(){ Count counter; counter.print(); setX(counter, 8); counter.print(); }

66

Design Patterns Consider previous solutions to problems similar to any new problem ▫ must have some characteristics in common ▫ tweak the solution Very few really new problems Whole bunch of patterns are documented that you can use

What is a design pattern? Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such a way that you can use this solution a million times over, without ever doing it the same way twice. Christopher Alexander Aid in discussing structures and relationships at a higher level of abstraction (viewed as a community of interacting agents)

Two Reasons to use design patterns Speeds process of finding a solution ▫ don’t reinvent the wheel Naming patterns gives programmers a common vocabulary or language to discuss design alternatives.

Easy Example: Adapter Pattern An object in your community (client) needs a service and requires a specific interface Another object provides the service, but does not support the desired interface CREATE AN ADAPTER! ▫ speaks the language of the client, but doesn’t do the work itself, it gets the service to do it

Singleton Pattern Not all patterns deal with client/server interactions In Singleton pattern the developer of a class wants to ensure there is never more than one instance of the class

Decorator Pattern Decorator pattern deals with how new functionality can be attached to existing objects ▫ inheritance is one way to do this ▫ inheritance is static and heavyweight ▫ inheritance does not permit values to change their behavior dynamically during execution A decorator wraps around an existing object and satisfies the same requirements ▫ delegates much of responsibility to original ▫ occasionally adds new functionality

Observer Pattern Addresses problem of how two objects can stay synchronized without having direct knowledge of each other

Study questions pg 233: 1-3, 8,9 pg. 273: 2, 4 pg. 286: 2-6 pg. 307: 2, 4,6 pg. 332: 2-3, 8, 9 pg. 387: 5 pg. 461: 2, 5-7, 9, 14 pg. 478: 1, 3, 5, 15 74