paradigm of the object oriented programming, class, object
Post on 15-Jan-2016
232 Views
Preview:
TRANSCRIPT
Paradigm of the object Paradigm of the object oriented programming,oriented programming,
class, objectclass, object
ParadigmParadigm
paradigmparadigm (Collins English Dictionary) — (Collins English Dictionary) — a a very general conception of the nature of very general conception of the nature of
scientific endeavour within which a given scientific endeavour within which a given enquiry is undertakenenquiry is undertaken
programming paradigmsprogramming paradigms structural programmingstructural programming object oriented programmingobject oriented programming
Paradigm of the object oriented Paradigm of the object oriented programmingprogramming
object oriented programming object oriented programming — — aa parad paradiigm gm of of programming by use of programming by use of obobjjeectscts, , interpreting a interpreting a programming problem as a set of programming problem as a set of obobjjeects and cts and
as a relations among objects.as a relations among objects.
ObjectObject
Common understanding of „object”Common understanding of „object” „„Object” in programmingObject” in programming
It represents (in the program) real-life or abstract It represents (in the program) real-life or abstract objects (in the common understanding of object)objects (in the common understanding of object)
It’s a generalized variable (structure)It’s a generalized variable (structure) It is being defined and used according to syntactic It is being defined and used according to syntactic
and semantic rules of the programming languageand semantic rules of the programming language
Object - a generalized variable Object - a generalized variable (structure)(structure)
StructureStructure set of data elementsset of data elements, , usually of different typesusually of different types
GGeneralizedeneralized obobjectject = = datadata + met + methods for manipulating datahods for manipulating data
Object - Object - examplesexamples
Many objectsMany objects
usually many objects share specific set of usually many objects share specific set of attributes (features, qualities), we do need to attributes (features, qualities), we do need to define the set once, and to use it several timesdefine the set once, and to use it several times
class class — a group of things, people, etc., — a group of things, people, etc., possessing some quality or qualities in possessing some quality or qualities in
common; common;
We do need a class for all the similar objectsWe do need a class for all the similar objects
Class in programmingClass in programming
Class in programming—generalized type defined by Class in programming—generalized type defined by the user (of the language, i.e. by programmer)the user (of the language, i.e. by programmer)
it is used for defining objects (generalized variables)it is used for defining objects (generalized variables) providers programmer with lots of new and exciting providers programmer with lots of new and exciting
possibilities (to be discussed later :-)possibilities (to be discussed later :-) The class should The class should clearlyclearly represent specific concept, represent specific concept,
idea, or real-life being, that is not yet described by idea, or real-life being, that is not yet described by approppriate typeapproppriate type
Why object oriented programming?Why object oriented programming?
next stage in the SE evolutionnext stage in the SE evolution:: structuralstructural proceduralprocedural modularmodular
tool for implementong OO projects (there is OO tool for implementong OO projects (there is OO analysis, OO design)analysis, OO design) languages that support OO programming languages that support OO programming
C++, Java, …C++, Java, … languages that permit OO programminglanguages that permit OO programming
all (programming languages)all (programming languages)
A structural example – personA structural example – person
struct personstruct person{{
int age;int age;char FName[20], LName[30];char FName[20], LName[30];
};};
void person_input(person *o);void person_input(person *o);void person_set(person *o, int age, char *void person_set(person *o, int age, char *ppFN, char *FN, char *ppLN);LN);void person_output(person *o);void person_output(person *o);
no access controll over data membersno access controll over data members it’s a pogrammer responsibility to use proper functions for manipulating it’s a pogrammer responsibility to use proper functions for manipulating
personspersons
An OO example – personAn OO example – person
class class personperson{{
int int ageage;; // class members – // class members – class variablesclass variableschar char FNameFName[20], [20], LNameLName[30];[30];
public:public:void void inputinput();(); // class members – // class members – class methodsclass methodsvoid void setset(int (int ageage, char *p, char *pFNFN, char *p, char *pLNLN););void void outputoutput();();
}; }; // declaration ends with „ // declaration ends with „ ;; ” ”
data and methods togetherdata and methods together default for class: no external access to class variablesdefault for class: no external access to class variables
CClass memberslass members access rules access rules
private:private:// // private membersprivate members// accessible for methods of this class// accessible for methods of this class,, // // and and for methods and functios declared as friendsfor methods and functios declared as friends// all „class” members are private by default// all „class” members are private by default
public:public:// // public memberspublic members// accessible from outside the class // accessible from outside the class // all „struct” members are public by default// all „struct” members are public by default
protected:protected:// // protected membersprotected members // access like to private members// access like to private members// but the derived class also may access this members// but the derived class also may access this members
CClass memberslass members access rules access rules
class class personperson
{{
int int ageage;; // private// private
char char FNameFName[20][20];; // private// private
public:public:
void void inputinput(); (); // public// public
private:private:
char char LNameLName[30];[30]; // private// private
public:public:
void void setset(int, char *, char *);(int, char *, char *); // public// public
void void outputoutput();(); // public// public
};};
Hermetization, EncapsulationHermetization, Encapsulation
Gathering all data and methods in single classGathering all data and methods in single class (encapsulation) (encapsulation) allows the programmer to allows the programmer to decide and restrict access to class members decide and restrict access to class members
(hermet(hermetizationization)). .
AAll ll the the class members are private by defaultclass members are private by default OOOP ;-) OOOP ;-) — — orthodox OO programming: all orthodox OO programming: all
class data members are private, from outside class data members are private, from outside we access them through class methods we access them through class methods onlyonly..
Object - a generalized structureObject - a generalized structure
Declaring:Declaring:
class personclass person meme, , You;You;
personperson bossboss;; // while declaring/defining obiect// while declaring/defining obiect
// „class”, „struct” or „union” may be skipped// „class”, „struct” or „union” may be skipped UsingUsing
bossboss..inputinput();();
bossboss..outputoutput();();
Operators for accessingOperators for accessingclass membersclass members
dot „ dot „ . . ””objectobject..variable;variable; //// just like in C just like in C strustructurectureobjectobject..method(); method(); // encapsulation// encapsulation
scope operator „ scope operator „ :::: „ „classclass::::variable;variable; // // sizeofsizeof, static variables, static variablesclassclass::::methodmethod()();; // // definidefining methods, static methodsng methods, static methods
Scope definition ( object. and class::) usually may be skippedScope definition ( object. and class::) usually may be skipped class method accessing members of its own classclass method accessing members of its own class declaring/defining methods inside class declatationdeclaring/defining methods inside class declatation
How to define methods?How to define methods? Inside class declatationInside class declatation
class class personperson{{
……
void void inputinput()(){{
cin>>age>>FName>>LName;cin>>age>>FName>>LName;} } // semicolon not required// semicolon not required
……};};
above is above is inlineinline by default by default
How to define methods?How to define methods? outside the class use the scope operator outside the class use the scope operator by default, such method is not inlineby default, such method is not inline
void void personperson::::setset(int (int ageage, char *p, char *pFNFN, char *p, char *pLNLN)){{
osoba::osoba::ageage==ageage; ; // // scope operator since local argument „age” visible, not personscope operator since local argument „age” visible, not person::::ageagestrcpy(strcpy(FNameFName, , pFNpFN););strcpy(strcpy(LNameLName, p, pLNLN););
}}
want the method to be inline?want the method to be inline?
inlineinline void void personperson::::outputoutput()(){{ cout<<„cout<<„ageage: "<<: "<<ageage<<" <<" first namefirst name: "<<: "<<FNameFName<<" <<" lastlast: "<<: "<<LNameLName<<"\n";<<"\n";}}
How to define methods?How to define methods? when creating libraries we place class declaration and definitions of inline when creating libraries we place class declaration and definitions of inline
methods in the header file (*.h), other methods in *.cpp.methods in the header file (*.h), other methods in *.cpp.
Methods just like functions may (and often are) overloaded, and may have Methods just like functions may (and often are) overloaded, and may have default argumentsdefault arguments
void void setset(int, char *(int, char *pFNpFN="Jan", char *="Jan", char *pLNpLN="Kowalski");="Kowalski");void void setset((const person & exampleconst person & example););
boss.set(You); boss.set(You); boss.set(50, „Osama”, „bin Laden”); boss.set(50, „Osama”, „bin Laden”); boss.set(50, „Osama”);boss.set(50, „Osama”);boss.set(50);boss.set(50);// boss.set(); ERROR!// boss.set(); ERROR!
How to define methods?How to define methods? methods and variables defined in class are visible from the beginning of methods and variables defined in class are visible from the beginning of
the class definition. They are also visible in class methods declared in the the class definition. They are also visible in class methods declared in the class, but defined outsideclass, but defined outside
class Aclass A{{public:public:
void void inputinput()(){{
cin>>i;cin>>i; // // declaration of „i” is belowdeclaration of „i” is belowoutputoutput();(); // // as aboveas above
}}
void void outputoutput();();int i;int i;
};};
How to define methods?How to define methods? To remind: from outside class methods, the class To remind: from outside class methods, the class
members must be specified either by class name, or members must be specified either by class name, or by object nameby object name
int test()int test(){{
A a;A a;
int j=sizeof(A::i);int j=sizeof(A::i);void (A::*p)()=&A::void (A::*p)()=&A::inputinput;;a.i=3;a.i=3; // i is public in A// i is public in A
}}
The scope operator as a not OO C++ The scope operator as a not OO C++ extensionextension
int fun();int fun();
int i;int i;
class Cclass C
{{
int i;int i;
public:public:
void test();void test();
int fun();int fun();
};};
void C::test()void C::test()
{{
i++;i++; // C::i// C::i++++
::i++;::i++; // global i// global i
fun();fun(); // C::fun()// C::fun()
::fun();::fun(); // globa// global l funfun()()
}}
ExampleExample
TaskTask declare the declare the pointpoint class, that represents 2D class, that represents 2D
pointspoints no public data membersno public data members public methodspublic methods: : inputinput, , outputoutput, , movemove ((by a vector by a vector
specified by a pair of coordinatesspecified by a pair of coordinates), ), distancedistance ((between this point and the method argument - a between this point and the method argument - a reference to pointreference to point)),, met methodshods coordXcoordX i i coordYcoordY that that return appropriate coordinate of the pointreturn appropriate coordinate of the point
ExampleExample
class class pointpoint{{
double x, y;double x, y;
public:public:void void inputinput();();void void outputoutput();();void void movemove(double dx, double dy);(double dx, double dy);double double distancedistance((const const punkt &p);punkt &p);double double coordXcoordX();(); // // a.k.a. accessorsa.k.a. accessorsdouble double coordYcoordY();();
};};
ExampleExample
TaskTask define inline methods define inline methods
input()input()
output()output()
move()move()
distance()distance()
ExampleExample
class class pointpoint{{
double x, y;double x, y;public:public:
void void inputinput() {cin>>x>>y; };() {cin>>x>>y; };void void outputoutput() {cout<<x<<y; };() {cout<<x<<y; };……
};};
inline void inline void pointpoint::::movemove(double dx, double dy)(double dx, double dy){{
x+=dx;x+=dx;y+=dy;y+=dy;
}}
ExampleExample
inline double inline double pointpoint::::distancedistance((pointpoint &p) &p)
{{
return sqrt( (x-p.x)*(x-p.x) + (y-p.y)*(y-p.y) );return sqrt( (x-p.x)*(x-p.x) + (y-p.y)*(y-p.y) );
}}
remark:remark: „private” is defined for the whole „private” is defined for the whole class, not for the single object only.class, not for the single object only.
Classes and Abstract Data TypesClasses and Abstract Data Types classes are perfectly suitable for implementing classes are perfectly suitable for implementing
Abstract Data TypesAbstract Data Types classes classes areare Abstract Data Types Abstract Data Types
We define class interface – when we use methods We define class interface – when we use methods allowed for the specific class, we do not care how the allowed for the specific class, we do not care how the methods are implemented. Thanks to hermetization methods are implemented. Thanks to hermetization implementation details are separated from the class implementation details are separated from the class interface. interface.
Examples: stack, queue, Examples: stack, queue, pointpoint, segment, segment
ExampleExample
TaskTask declare the declare the pointpoint class, that represents 2D class, that represents 2D
segmentssegments no public data membersno public data members public methodspublic methods: : inputinput, , outputoutput, , movemove ((by a vector by a vector
specified by a pair of coordinatesspecified by a pair of coordinates), ), lengthlength ( (length length of a segmentof a segment))..
ExampleExampleclass class segmentsegment{{
pointpoint p1, p2; p1, p2;public:public:
void void inputinput()(){{
p1.p1.inputinput();();p2.p2.inputinput();();
}}void void outputoutput()(){{
p1.p1.outputoutput();();p2.p2.outputoutput();();
}}
void void movemove(double dx, double dy)(double dx, double dy){{
p1. p1. movemove(dx, dy);(dx, dy);p2. p2. movemove(dx, dy);(dx, dy);
}}double double lengthlength()(){{
return p1.return p1.distancedistance(p2);(p2);}}
};};
Interesting fact: nested class Interesting fact: nested class declarationsdeclarations
class declarationclass declaration may be nested inside other may be nested inside other class declarationclass declaration
nested class is not visible in the global scopenested class is not visible in the global scope
Interesting fact: nested class Interesting fact: nested class declarationsdeclarations
class Xclass X{{
class M1class M1{{
int m;int m;};};
public:public:class M2class M2
{{int m;int m;
};};};};
void f()void f(){{
M1 m1;M1 m1; // // errorerror // not in global scope// not in global scope
X::M1 xm1;X::M1 xm1; // // errorerror ////M1 M1 is a private class inis a private class in X X
X::M2 xm2;X::M2 xm2; // ok. // ok. }}
Interesting fact: nested class Interesting fact: nested class declarationsdeclarations
X X has neither member variables nor member methodshas neither member variables nor member methods, it contains only types (still, , it contains only types (still, we may create objects of this class).we may create objects of this class).class with nested class class with nested class andand class variables: class variables:
class X_dclass X_d{{public:public:
class M2class M2{{
int m;int m;};};
M2 m2;M2 m2; // here // here};};
generally nested class declarations are to be avoided generally nested class declarations are to be avoided and actually are used rarelyand actually are used rarely (except very small classes) — nested class declarations are barely usefull and (except very small classes) — nested class declarations are barely usefull and barely visible. barely visible.
top related