object oriented programming and object oriented design
Post on 06-Jan-2016
116 Views
Preview:
DESCRIPTION
TRANSCRIPT
Object Oriented Object Oriented ProgrammingProgramming
andandObject Oriented DesignObject Oriented Design
Programming LanguagesProgramming Languages
Robert DewarRobert Dewar
Object Oriented ProgrammingObject Oriented Programming
OOP provides three fundamental OOP provides three fundamental functionalities:functionalities:Type extensionType extensionInheritanceInheritanceDynamic PolymorphismDynamic Polymorphism
Type ExtensionType Extension
The problem, given an existing type, The problem, given an existing type, add additional capabilities retaining add additional capabilities retaining the originalthe original
Make the extended type look as Make the extended type look as much like the original as possiblemuch like the original as possible
Typical implementation, add fields or Typical implementation, add fields or components to an existing record components to an existing record type.type.
Faking Type ExtensionFaking Type Extension
Could make a new recordCould make a new recordWith new componentsWith new componentsAnd retaining the old type as one componentAnd retaining the old type as one component
typetype Ext Ext is recordis record Parent : Old; Parent : Old; Newf : Integer; Newf : Integer;end recordend record;;
But that would not look much like originalBut that would not look much like originalIf Newobj is of type ExtIf Newobj is of type Ext
Cannot say Ext.ValueCannot say Ext.ValueMust say Ext.Parent.ValueMust say Ext.Parent.Value
InheritanceInheritance
Goes along with type extensionGoes along with type extensionWhen a type is extendedWhen a type is extended
New type has all the operations of the New type has all the operations of the old type, with the same meaning.old type, with the same meaning.
Of course they do not know about the Of course they do not know about the new fields, and do not reference themnew fields, and do not reference them
But most code that worked for the base But most code that worked for the base type works for the extended type type works for the extended type without changewithout change
More on InheritanceMore on Inheritance
Cannot always use operations of base Cannot always use operations of base typetypeMay need to mess with new fieldsMay need to mess with new fields
In particular constructors must do soIn particular constructors must do soMay have different semantics from new May have different semantics from new
fieldfieldShould be able to “override” inherited Should be able to “override” inherited
operations when type is extendedoperations when type is extendedMust override constructorsMust override constructors
Can also add new operations for new Can also add new operations for new extended typeextended type
Faking InheritanceFaking Inheritance
If you fake type extensionIf you fake type extensionYou could add definitions for every You could add definitions for every
operation. Most would look likeoperation. Most would look likeprocedureprocedure Operate (X : Ext) Operate (X : Ext) isis
beginbegin Operate (X.Parent); Operate (X.Parent);
endend Operate; Operate;
That’s rather annoyingThat’s rather annoyingAnd generates a lot of junkAnd generates a lot of junk
Ad Hoc PolymorphismAd Hoc Polymorphism
More familiar term is overloadingMore familiar term is overloadingApplies in this situation as followsApplies in this situation as follows If we have several types derived from a If we have several types derived from a
common parent with an operation common parent with an operation OpOpSuppose Suppose OpOp is overridden for some is overridden for some
typestypes If a variable has a particular type, then If a variable has a particular type, then
the compiler can figure out what the compiler can figure out what OpOp you mean from the type of the variableyou mean from the type of the variable
Dynamic PolymorphismDynamic Polymorphism
Also called dynamic dispatchingAlso called dynamic dispatchingAddresses problems where you have Addresses problems where you have
data structures that are heterogenous data structures that are heterogenous and can contain different kinds of data.and can contain different kinds of data.
The data items are similar (e.g. The data items are similar (e.g. obtained by type extension from a obtained by type extension from a common base).common base).
And therefore have a similar set of And therefore have a similar set of operations.operations.
More on Dynamic DispatchingMore on Dynamic Dispatching
Now suppose we apply Now suppose we apply OpOp to a to a variable which at run time can have variable which at run time can have more than one possible “type”.more than one possible “type”.
What we want is that at runtime, the What we want is that at runtime, the proper proper OpOp is picked, based on the is picked, based on the current type of the object in the current type of the object in the variablevariable
This is called dynamic dispatchingThis is called dynamic dispatching
Faking Dynamic DispatchingFaking Dynamic Dispatching
We could have record fields that We could have record fields that contained pointers to the function to be contained pointers to the function to be called.called.
Actually that’s how dynamic dispatching Actually that’s how dynamic dispatching is usually implemented:is usually implemented:Record contains a pointer to a tableRecord contains a pointer to a tableTable has (at fixed offsets for any given Table has (at fixed offsets for any given
operation), address of function to be called.operation), address of function to be called.Different types have different tablesDifferent types have different tables
An Approach to CompareAn Approach to Compare
The issue is that we want a variable The issue is that we want a variable that can have several different forms that can have several different forms at runtime.at runtime.
And we have some code that And we have some code that depends on which particular form it depends on which particular form it has.has.
And some code that is the same for And some code that is the same for all types.all types.
Using Variant RecordsUsing Variant Records
Instead of N types extended from a Instead of N types extended from a given base type, use a variant record given base type, use a variant record with N different possibilities.with N different possibilities.
Fields of parent correspond to Fields of parent correspond to common fields in the variant recordcommon fields in the variant record
Code that does not depend on type Code that does not depend on type just accesses these common fieldsjust accesses these common fields
Using Variant Records (cont)Using Variant Records (cont)
Code that is not common has a case Code that is not common has a case statement:statement:casecase Object.DiscrimValue Object.DiscrimValue isis
whenwhen val1 => … val1 => …whenwhen val2 => … val2 => ………
end caseend case;;
Comparing the ApproachesComparing the Approaches
Consider that you have N operations Consider that you have N operations and T types, then potentially you have and T types, then potentially you have N*T different functions, but in practice N*T different functions, but in practice many of the functions are the same many of the functions are the same for many types.for many types.
Case statement means you have one Case statement means you have one unit per operation, using case to selectunit per operation, using case to select
Dynamic dispatching means you have Dynamic dispatching means you have one unit per type, with overridden one unit per type, with overridden operations.operations.
Comparing the Approaches Comparing the Approaches (cont.)(cont.)
If you often add operations, the case If you often add operations, the case statement approach is easier, add one statement approach is easier, add one new unit for new operation providing new unit for new operation providing base code with case statements as base code with case statements as requiredrequired
If you often add types, the dynamic If you often add types, the dynamic dispatching approach is easier, add one dispatching approach is easier, add one new unit for new type overriding any new unit for new type overriding any operations where base code is wrong.operations where base code is wrong.
OOP and ReuseOOP and Reuse
By making your types extendibleBy making your types extendibleYou increase reuse capabilitiesYou increase reuse capabilities Instead of editing your code in places Instead of editing your code in places
where it does not applywhere it does not applyA client extends your types, and A client extends your types, and
overrides your code where it does overrides your code where it does not applynot apply
Object Oriented DesignObject Oriented Design
Has nothing to do with OOP per seHas nothing to do with OOP per seRelates not to language features but Relates not to language features but
to the design approachto the design approach It may be that OOP features are It may be that OOP features are
useful for object oriented design useful for object oriented design (OOD).(OOD).
OOD – The Basic IdeaOOD – The Basic Idea
The problem is modeled as a set of The problem is modeled as a set of objects, preferably related to the objects, preferably related to the structure of the problem, that structure of the problem, that represent real objects in the world. represent real objects in the world. These objects have state.These objects have state.
Computation proceeds by passing Computation proceeds by passing messages (requests, signals, messages (requests, signals, commands, reports) between commands, reports) between objects.objects.
How does OOD relate to OOPHow does OOD relate to OOP
In the real world, objects are built by In the real world, objects are built by specializing more general notionsspecializing more general notions
A Toyota Previa is an instance of Car with A Toyota Previa is an instance of Car with extra info, which is an instance of Vehicle extra info, which is an instance of Vehicle with extra information, etc.with extra information, etc. Type extensionType extension
All cars work mostly the sameAll cars work mostly the same InheritanceInheritance
But for some features, cars differBut for some features, cars differ Dynamic dispatching Dynamic dispatching
OOP Features in Ada 83OOP Features in Ada 83
Ada 83 provides features forAda 83 provides features forInheritanceInheritance
But does not provideBut does not provideType extension Type extension Dynamic dispatchingDynamic dispatching
Inheritance is provided via derived typesInheritance is provided via derived typesOther OOP features deliberately omittedOther OOP features deliberately omitted
Designers were very familiar with Simula-67Designers were very familiar with Simula-67But felt that genericity was a better But felt that genericity was a better
approachapproach
Derived TypesDerived Types
Declare a type and some operations on Declare a type and some operations on itit
typetype Base Base isis …. ….procedureprocedure Print (Arg : Base); Print (Arg : Base);functionfunction New_Base New_Base returnreturn Base; Base;
Now derive a new typeNow derive a new typetypetype Mybase Mybase is newis new Base; Base;
All operations are available on MybaseAll operations are available on MybaseIncluding for example Print and Including for example Print and
New_BaseNew_BaseBut you can redefine (override) any But you can redefine (override) any
inherited operations.inherited operations.
OOP In Ada 95OOP In Ada 95
Genericity is not enoughGenericity is not enoughMarket demands OOP featuresMarket demands OOP featuresSo in Ada 95 features are added forSo in Ada 95 features are added for
Type ExtensionType ExtensionDynamic DispatchingDynamic DispatchingBut multiple inheritance is deliberately But multiple inheritance is deliberately
omittedomitted
Tagged Types in Ada 95Tagged Types in Ada 95
A tagged type has a dynamic tag A tagged type has a dynamic tag showing what type the object is. showing what type the object is. Otherwise it looks like a recordOtherwise it looks like a record
typetype Base Base is tagged recordis tagged record X : Integer; X : Integer; Y : Float; Y : Float;end recordend record;;
Can also have tagged private typesCan also have tagged private typestypetype Base Base is tagged privateis tagged private;;
Completion must be tagged record Completion must be tagged record
Type ExtensionType Extension
A tagged type can be extendedA tagged type can be extended Using an extension of derived type ideaUsing an extension of derived type idea
typetype Mybase Mybase is newis new Base Base with recordwith record B : Boolean; B : Boolean; D : Duration; D : Duration;end recordend record;;
All operations are inheritedAll operations are inherited Except for constructors (functions returning Except for constructors (functions returning
values of type Base)values of type Base)Constructors must be overriddenConstructors must be overriddenSince they need to know about the new fieldsSince they need to know about the new fields
How type Extension WorksHow type Extension Works
New fields are added at the end of the New fields are added at the end of the record, with original fields at the start.record, with original fields at the start.
A subprogram that is only referencing the A subprogram that is only referencing the original fields can do this on the base type original fields can do this on the base type or any type derived from it.or any type derived from it.
Because the original fields are always at Because the original fields are always at the same offset from the start of the the same offset from the start of the record.record.
This model does not extend well to the This model does not extend well to the case of multiple inheritance.case of multiple inheritance.
Type extension and Type extension and overloadingoverloading
Suppose a client hasSuppose a client hasB : Base;B : Base;M : Mybase;M : Mybase;
And there is an operation D that was not And there is an operation D that was not overridden:overridden:D (B); D (M);D (B); D (M);Correct proc called, but in fact does same thingCorrect proc called, but in fact does same thing
And there was an overridden operation OAnd there was an overridden operation OO (B); O (M);O (B); O (M);Correct proc called (static overloading)Correct proc called (static overloading)
Converting Among TypesConverting Among Types
Suppose we have an operation Q that is Suppose we have an operation Q that is defined for Base and was not inheriteddefined for Base and was not inheritedBecause it was not defined in original Because it was not defined in original
packagepackageAnd now we have a Mybase:And now we have a Mybase:
M : Mybase;M : Mybase;
And we want to call Q on M:And we want to call Q on M:Q (M); Q (M); -- no good, wrong type -- no good, wrong typeQ (Base (M)) -- that’s ok, a view conversionQ (Base (M)) -- that’s ok, a view conversion
Using conversion when Using conversion when OverridingOverriding
Suppose we have a procedure Dump Suppose we have a procedure Dump defined on Basedefined on Base
For Mybase we want to dump the For Mybase we want to dump the new fields and then call the original new fields and then call the original dumpdump
procedureprocedure Dump (X : Mybase) Dump (X : Mybase) isisbeginbegin … dump new fields … dump new fields Dump (Base (X)); -- calls original Dump Dump (Base (X)); -- calls original Dumpendend Dump; Dump;
Converting the Other Way: Converting the Other Way: NOTNOT
Suppose we have an operation M Suppose we have an operation M that is defined for Mybase, and we that is defined for Mybase, and we have an object of type Base:have an object of type Base:
B : Base;B : Base;And we want to apply M to BAnd we want to apply M to BYou are out of luck, can’t do itYou are out of luck, can’t do itAfter all M might refer to extended After all M might refer to extended
fields!fields!
Class VariablesClass Variables
Suppose you want a data structure Suppose you want a data structure that holds a mixture of objects of that holds a mixture of objects of type Base and Mybase.type Base and Mybase.
The type Base’Class is a type that The type Base’Class is a type that includes values of tagged type Base includes values of tagged type Base and all types derived from Base.and all types derived from Base.typetype Bptr is Bptr is accessaccess Base’Class; Base’Class;BC_Ptr : Bptr := new Base’(….);BC_Ptr : Bptr := new Base’(….);
BC_Ptr := new Mybase’(….);BC_Ptr := new Mybase’(….);
Dynamic DispatchingDynamic Dispatching
If a subprogram, say Draw is defined If a subprogram, say Draw is defined as a primitive operation of type Base as a primitive operation of type Base (defined along with type Base)(defined along with type Base)
Then not only is it inherited by any Then not only is it inherited by any type derived from Basetype derived from Base
But it is also defined on Base’ClassBut it is also defined on Base’Class
Special Treatment of Special Treatment of Base’ClassBase’Class
The subprogramThe subprogramprocedureprocedure Draw (Arg : Base’Class); Draw (Arg : Base’Class);
That is derived automaticallyThat is derived automaticallyHas special semanticsHas special semanticsIt is called with an object of the It is called with an object of the
appropriate type (e.g. BC_Ptr.appropriate type (e.g. BC_Ptr.all)all)The result is to call the version of Draw The result is to call the version of Draw
that is appropriate to the actual run-time that is appropriate to the actual run-time type of the argument (looks at the tag)type of the argument (looks at the tag)
How Dynamic Dispatching How Dynamic Dispatching WorksWorks
Tag is actually a pointer to a tableTag is actually a pointer to a tableOne table for each typeOne table for each type
In our example, two tablesIn our example, two tablesOne table for BaseOne table for BaseDifferent table for MybaseDifferent table for Mybase
Table contains pointers to subprogramsTable contains pointers to subprogramsPut new ones at endPut new ones at endFirst entries in Mybase table are a copy of First entries in Mybase table are a copy of
the entries in the Base table unless the entries in the Base table unless overridden.overridden.
Object-Oriented Object-Oriented programming in C++programming in C++
Classes as units of encapsulationClasses as units of encapsulation Information HidingInformation Hiding Inheritance Inheritance polymorphism and dynamic dispatchingpolymorphism and dynamic dispatching Storage managementStorage management multiple inheritancemultiple inheritance
ClassesClasses
Encapsulation of type and related operationsEncapsulation of type and related operationsclassclass point { point {
doubledouble x,y; x,y; // private data members// private data members
publicpublic::
point (point (intint x0, x0, intint y0); y0); // public methods// public methods
point () { x = 0; y = 0;}; point () { x = 0; y = 0;}; // a constructor// a constructor
voidvoid move ( move (intint dx, dx, intint dy); dy);
voidvoid rotate ( rotate (doubledouble alpha); alpha);
intint distance (point p); distance (point p);
}}
A class is a type : objects are A class is a type : objects are instancesinstances
point p1 (10, 20); point p1 (10, 20); // call constructor with given arguments// call constructor with given arguments
point p2; point p2; // call default constructor// call default constructor
Methods are functions with an implicit argumentMethods are functions with an implicit argument
p1.move (1, -1); p1.move (1, -1); // special syntax to indicate object// special syntax to indicate object
// in other languages might write // in other languages might write move (p1, 1, -1)move (p1, 1, -1)
// special syntax inspired by message-passing metaphor:// special syntax inspired by message-passing metaphor:
// objects are autonomous entities that exchange // objects are autonomous entities that exchange messagesmessages..
Implementing methodsImplementing methods
No equivalent of a body: each method can be defined No equivalent of a body: each method can be defined separatelyseparately
voidvoid point::rotate ( point::rotate (doubledouble alpha) { alpha) {
x = x * cos (alpha) - y * sin (alpha);x = x * cos (alpha) - y * sin (alpha);
y = y * cos (alpha) + x * cos (alpha);y = y * cos (alpha) + x * cos (alpha);
};};
// x and y are the data members of the object on which // x and y are the data members of the object on which thethe
// method is being called.// method is being called.
// if method is defined in class declaration, it is inlined.// if method is defined in class declaration, it is inlined.
ConstructorsConstructors
One of the best innovations of C++One of the best innovations of C++ special method (s) invoked automatically when special method (s) invoked automatically when
an object of the class is declaredan object of the class is declared point (point (intint x1, x1, intint x2); x2);
point ();point ();
point (point (doubledouble alpha; alpha; doubledouble r); r);
point p1 (10,10), p2; p3 (pi / 4, 2.5);point p1 (10,10), p2; p3 (pi / 4, 2.5); Name of method is name of className of method is name of class Declaration has no return type.Declaration has no return type.
The target of an operationThe target of an operation
The implicit parameter in a method call can be The implicit parameter in a method call can be retrieved through retrieved through thisthis::
classclass Collection { Collection {
Collection& insert (thing x) { Collection& insert (thing x) { // return reference// return reference
… … modify data structuremodify data structure
returnreturn * *thisthis; ; // to modified object// to modified object
};};
};};
my_collection.insert (x1).insert (x2);my_collection.insert (x1).insert (x2);
Static membersStatic members
Need to have computable attributes for class Need to have computable attributes for class itself, independent of specific object; e.g. number itself, independent of specific object; e.g. number of objects created.of objects created.
Static qualifier indicates that entity is unique for Static qualifier indicates that entity is unique for the classthe class
staticstatic intint num_objects = 0; num_objects = 0;
point () { num_objects++;}; point () { num_objects++;}; // ditto for other // ditto for other constructorsconstructors
Can access static data using Can access static data using class nameclass name or or object object name:name:
ifif (point.num_objects != p1.num_objects) error (); (point.num_objects != p1.num_objects) error ();
Classes and private typesClasses and private types
If all data members are private, class is identical If all data members are private, class is identical to a private type: visible methods, including to a private type: visible methods, including assignment.assignment.
A A structstruct is a class with all public members is a class with all public members How much to reveal is up to programmerHow much to reveal is up to programmer define functions to retrieve (define functions to retrieve (not modifynot modify) private ) private
datadata intint xcoord () { xcoord () { returnreturn x;}; x;};
intint ycoord () { ycoord () { returnreturn y;}; y;};
p2.x = 15; p2.x = 15; // error, data member x is // error, data member x is
privateprivate
DestructorsDestructors
If constructor allocates dynamic storage, need to If constructor allocates dynamic storage, need to reclaim itreclaim it
classclass stack { stack { intint* contents; * contents; intint sz; sz; publicpublic:: stack (stack (intint size) { contents = size) { contents = newnew int int [ sz = size];};[ sz = size];}; voidvoid push (); push (); intint pop (); pop (); intint size () { size () { returnreturn sz;}; } sz;}; }
stack my_stack (100); stack my_stack (100); // allocate storage dynamically// allocate storage dynamically
// when is // when is my_stack.contentsmy_stack.contents released? released?
If constructor uses resources, class If constructor uses resources, class needs a destructorneeds a destructor
User cannot deallocate data because data User cannot deallocate data because data member is private: system must do itmember is private: system must do it
~stack ( ) {~stack ( ) {deletedelete[ ] contents;};[ ] contents;}; inventive syntax:inventive syntax: negation of constructor negation of constructor Called Called automaticallyautomatically when object goes out of when object goes out of
scopescope Almost never called explicitlyAlmost never called explicitly
Copy and assignmentCopy and assignment
point p3 (10,20);point p3 (10,20);
point p5 = p3; point p5 = p3; // componentwise copy// componentwise copy
This can lead to unwanted sharing:This can lead to unwanted sharing:
stack stack1 (200);stack stack1 (200);
stack stack2 = stack1; stack stack2 = stack1; // stack1.contents // stack1.contents sharedshared
stack2.push (15); stack2.push (15); // stack1 is modified// stack1 is modified
Need to redefine assignment and copyNeed to redefine assignment and copy
Copy constructorCopy constructor
stack (stack (constconst stack& s) { stack& s) { // reference to existing object// reference to existing object
contents = contents = new int new int [ sz = s.size()];[ sz = s.size()];
forfor ( (intint I = 0; I <sz; I++) contents [I] = s.contents [I]; I = 0; I <sz; I++) contents [I] = s.contents [I];
}}
stack s1 (100);stack s1 (100);
… …
stack s2 = s1; stack s2 = s1; // invokes copy constructor// invokes copy constructor
Redefining assignmentRedefining assignment
Assignment can also be redefined to avoid unwanted Assignment can also be redefined to avoid unwanted sharingsharing
Operator returns a reference, so it can be used efficiently Operator returns a reference, so it can be used efficiently in chained assignments: in chained assignments: one = two = threeone = two = three;;
stack & stack & operatoroperator= (= (constconst stack& s) { stack& s) { ifif ( (thisthis != &s) { != &s) { // beware of self-// beware of self-
assignmentassignment deletedelete [] contents; [] contents; // discard old value// discard old value contents = contents = newnew intint [sz = s.size ()]; [sz = s.size ()]; forfor ( (intint I = 0; I <sz; I++) contents [I] = s.contents [I]; I = 0; I <sz; I++) contents [I] = s.contents [I]; }} returnreturn * *thisthis; }; } stack s1 (100), s2 (200); … s1 = s2; stack s1 (100), s2 (200); … s1 = s2; // transfer // transfer
contentscontents
Differences Between Ada and Differences Between Ada and C++C++
C++ model much more specialized C++ model much more specialized to the notion of OODto the notion of OODDistinguished first parameter is object Distinguished first parameter is object
involvedinvolvedNo easy way of defining binary No easy way of defining binary
operatorsoperatorsPrefix notation nice for objects but Prefix notation nice for objects but
awkward for valuesawkward for valuesC++ allows multiple inheritanceC++ allows multiple inheritance
Doing Multiple Inheritance in Doing Multiple Inheritance in AdaAda
We can have one field that we add We can have one field that we add be an instance of some other base be an instance of some other base type.type.
We can use generics to parametrize We can use generics to parametrize this additional typethis additional type
Worked out examples in Ada 95 Worked out examples in Ada 95 RationaleRationaleWhich you can find at Which you can find at
www.adapower.comwww.adapower.com
OOP in JavaOOP in Java
To be supplied!To be supplied!
top related