74
ReviewSlides CMPS 2143

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

Embed Size (px)

Citation preview

ReviewSlides

CMPS 2143

2

CHAPTER 11

3

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:

function max (left, right) { if (left < right) return right; return left;}

4

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.

5

C++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 !

6

C++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

CHAPTER 12

8

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.)

9

Minimum Space Allocation

•Default: not all fields copied/only the corresponding fields. (termed slicing)

10

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.

11

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

12

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

13

CHAPTER 13

14

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!

15

CHAPTER 14

16

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

17

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) {…}}

18

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) {…}}

19

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.

20

Generics/Templates – More in Chapter 18

•A way of creating general purpose tools and specializing them to specific situations

template <class T> 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

21

CHAPTER 15

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- 1order (anApplePie, aDessert); //legal - 2order (aDessert, aDessert); //illegal

//all eliminated in step 1, can’t downcastorder (anApplePie, aChocolateCake); //legal

//all in set; 1,2 eliminated in step2, //because 3’s parameters more specificorder (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

CHAPTER 16-17

28

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

Parent

void method (int, float

Child

void method (int, float

AnotherChild

29

Overriding vs OverloadingOverloading Overriding

• 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

30

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.

31

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();

32

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

33

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 exampleclass 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”;}

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).

• Examplepublic 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 <Child *> (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

CHAPTER 18

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 <int> 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 declarationtemplate <class T>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 <class T>T NewClass::setData(const T & newValue ){ theData = T; //assumes = is defined for T} 

template <class T>NewClass <T> NewClass <T>::operator + (const NewClass<T> & newClass1, const NewClass<T> & newClass2) { NewClass <T> result; result = ??? return result; }

Methods

Ex2. Instead non-member function looks like

NewClass nmFunction(const NewClass & newClass1, const NewClass & newClass2){ . . .} 

template <class T>NewClass <T> nmFunction (const NewClass<T> & newClass1, const NewClass<T> & newClass2) { … }

• NOTE: The name NewClass is changed to NewClass <T> only when it is used as a class name 

void main(){ NewClass <int> myFirst; NewClass <int> mySecond (2);

NewClass <int> myThird (33); NewClass <double> myFourth (4.5);  myFirst.setData (5); cout << myFourth.getData() << endl;

myFirst = nmFunction (mySecond, myThird); . :

47

CHAPTER 19 - 20

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 containerbool hasMoreElements();//return true iff there are more elements to process

ItemType nextElement();//return next element

void reset();//start at first element

53

CHAPTER 23

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

CHAPTER 24

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

74

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