introduction to object-oriented programming

33
Introduction to Introduction to Object-oriented Object-oriented Programming Programming

Upload: audi

Post on 06-Jan-2016

50 views

Category:

Documents


1 download

DESCRIPTION

Introduction to Object-oriented Programming. OOP Concepts. Object-oriented vs Procedure-oriented Programming Objects and Classes Encapsulation and Information Hiding. Procedure-Oriented Programing. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Introduction to Object-oriented Programming

Introduction toIntroduction toObject-oriented Object-oriented Programming Programming

Page 2: Introduction to Object-oriented Programming

OOP ConceptsOOP Concepts

1.1. Object-oriented vs Procedure-Object-oriented vs Procedure-oriented Programmingoriented Programming

2.2. Objects and ClassesObjects and Classes

3.3. Encapsulation and Information Encapsulation and Information HidingHiding

Page 3: Introduction to Object-oriented Programming

Procedure-Oriented Procedure-Oriented ProgramingPrograming

In procedure-oriented programs In procedure-oriented programs (FORTRAN, COBOL, C, Pascal, BASIC, (FORTRAN, COBOL, C, Pascal, BASIC, etc.), emphasis is on etc.), emphasis is on sequence of sequence of commands (procedure) to the commands (procedure) to the computer.computer.

For example, the following algorithm For example, the following algorithm reads a list of items from a file, reads a list of items from a file, sorts the list, and sorts the list, and prints the sorted list.prints the sorted list.

Page 4: Introduction to Object-oriented Programming

Open (aFile) cout 0 while (not isEOF (aFile)) Read (anItem from aFile) count aList (count) anItem end While Close (aFile) Sort (aList) Print ( elements of aList)

Read, Sort, Print Read, Sort, Print (procedural)(procedural)

Page 5: Introduction to Object-oriented Programming

Object-oriented Object-oriented ProgrammingProgramming

As programs become complex, As programs become complex, procedural programming becomes procedural programming becomes inadequate—too many data and inadequate—too many data and actions to keep track of.actions to keep track of.

Many program behaviors are not Many program behaviors are not simply simply sequentialsequential but are but are concurrentconcurrent..

In OOP, a program consists of In OOP, a program consists of a collection of objects that interact a collection of objects that interact with each otherwith each other..

Page 6: Introduction to Object-oriented Programming

Emphasis on ObjectsEmphasis on Objects

aFile.open() while( aFile.EOF() is not true)    anItem = aFile.read()    aList.insertNewItem(anItem) end while aFile.close() aList.sort() aList.print()

Page 7: Introduction to Object-oriented Programming

In OOP Program, note…In OOP Program, note… Objects—e.g., Objects—e.g., aListaList and and aFileaFile—are the focus —are the focus

of program, not procedures.of program, not procedures. Each object possesses operations peculiar to Each object possesses operations peculiar to

it—e.g., it—e.g., aFile.aFile.open(),open(), aFile. aFile.close(),close(), aList.aList.readread(), aList.i(), aList.insertNewItemnsertNewItem(), (), aList.aList.sortsort()()

Objects are called (asked) to perform its Objects are called (asked) to perform its operation to get a job done—e.g., operation to get a job done—e.g., aFile.openaFile.open..

In OOP, the inner structure of In OOP, the inner structure of aListaList is not is not revealed to the user of the object—user revealed to the user of the object—user need not know whether it is an array, linked need not know whether it is an array, linked list, or something else.list, or something else.

Page 8: Introduction to Object-oriented Programming

Objects and ClassesObjects and Classes

An OO program consists of a collection An OO program consists of a collection of objects interacting with each other.of objects interacting with each other.

ClassClass A template for creating objectsA template for creating objects It consists of It consists of attributesattributes (characteristics) (characteristics)

and and methodsmethods ( (operationsoperations)) ObjectObject

An instance of a classAn instance of a class Many object can be created from a classMany object can be created from a class

Page 9: Introduction to Object-oriented Programming

Objects and ClassesObjects and Classes

Suppose you are writing a game that Suppose you are writing a game that involves several dogs, cats, and cars. involves several dogs, cats, and cars. (Use your imagination.)(Use your imagination.)

You need to define a You need to define a DogDog class. class. Here are some dog objects: Here are some dog objects:

Fido—a big brown bulldogFido—a big brown bulldog Lassie—a tall collie dogLassie—a tall collie dog Taro—a small, white akita dogTaro—a small, white akita dog

Page 10: Introduction to Object-oriented Programming

ObjectsObjects

Attributes: name = Fido breed = bulldog color = brown weight = 30 kg height = 50 cmOperations: bark() display()

Attributes: name = Lassie breed = collie color = brow weight = 25 kg height = 70 cmOperations bark() display()

Attributes: name = Taro breed = akita color = white weight = 10kg height = 30 cmOperations bark() display()

Dog objectDog object

Dog object

Page 11: Introduction to Object-oriented Programming

ClassClass A class A class

Is an Is an abstractionabstraction of the objects of the same of the objects of the same type. Fido, Lassie, and Taro are all type. Fido, Lassie, and Taro are all instancesinstances of the of the DogDog class. class.

Is a template for creating (specifying) Is a template for creating (specifying) objects of a particular type.objects of a particular type.

Is like a blueprint for creating objectsIs like a blueprint for creating objects Specifies attributes and methods Specifies attributes and methods

(operations)(operations) Each objects has Each objects has

Different Different attributesattributes values values SameSame operations operations

Page 12: Introduction to Object-oriented Programming

Class (cont.)Class (cont.)

A class is composed ofA class is composed of Class NameClass Name AttributesAttributes OperationsOperations

Once a class is defined, objects can Once a class is defined, objects can be created (instantiated) from it.be created (instantiated) from it.

Page 13: Introduction to Object-oriented Programming

Class DiagramClass Diagram

Dog

breedcolorweightheight

Bark()display()

Class name

Attributes

Operations

Car

makeengineSizecolormaxSpeed

Start()accelerate()stop()display()

Page 14: Introduction to Object-oriented Programming

PracticePractice

Specify some relevant attributes and Specify some relevant attributes and operations for the following classes.operations for the following classes. Bank AccountBank Account BookBook Browser windowBrowser window Circle (geometric figure)Circle (geometric figure) Rectangle (geometric figure)Rectangle (geometric figure)

Page 15: Introduction to Object-oriented Programming

OOP TerminologyOOP Terminology

AbstractionAbstraction: a definition that captures : a definition that captures general characteristics without detailsgeneral characteristics without details An abstract triangle is a 3-sided polygon. A An abstract triangle is a 3-sided polygon. A

specific triangle may be scalene, isosceles, specific triangle may be scalene, isosceles, or equilateralor equilateral

Data hidingData hiding: restricting access to : restricting access to certain members of an object. The certain members of an object. The intent is to allow only member functions intent is to allow only member functions to directly access and modify the to directly access and modify the object’s dataobject’s data

Page 16: Introduction to Object-oriented Programming

OOP Terminology (cont.)OOP Terminology (cont.)

EncapsulationEncapsulation: the bundling of an : the bundling of an object’s data and procedures into a object’s data and procedures into a single entitysingle entity

Page 17: Introduction to Object-oriented Programming

Object ExampleObject Example

7-17

Member variables (attributes)

double side;

Member functions

void setSide(double s) { side = s; }

int getSide() { return side; }

Square

Square object’s data item:

side

Square object’s functions:

setSide()

getSice()

Page 18: Introduction to Object-oriented Programming

C++ ClassC++ Class

class Square {private: double side;

public: double getSide(){return side;} void setSide(double s){side = s;}};

Page 19: Introduction to Object-oriented Programming

Class ExampleClass Example

class Squareclass Square {{ private: private:

int side;int side; public: public:

void setSide(int void setSide(int s)s)

{ side = s; }{ side = s; } double getSide()double getSide() { return side; }{ return side; }

};};

7-19

Access specifiers

Page 20: Introduction to Object-oriented Programming

More on Access More on Access SpecifiersSpecifiers

Can be listed in any order in a classCan be listed in any order in a class

Can appear multiple times in a classCan appear multiple times in a class

If not specified, the default is If not specified, the default is privateprivate

7-20

Page 21: Introduction to Object-oriented Programming

7.4 Introduction to 7.4 Introduction to ObjectsObjects

An object is an instance of a classAn object is an instance of a class Defined just like other variables Defined just like other variables

Square sq1, sq2;Square sq1, sq2; Can access members using dot Can access members using dot

operator operator sq1.setSide(5);sq1.setSide(5);

cout << sq1.getSide();cout << sq1.getSide();

7-21

Page 22: Introduction to Object-oriented Programming

Types of Member Types of Member FunctionsFunctions

Acessor functionAcessor function:: uses but does not uses but does not modify a member variablemodify a member variable

ex: ex: getSidegetSide

Mutator functionMutator function: modifies a member : modifies a member variablevariable

ex: ex: setSidesetSide Constructor: Constructor: creaes an instance of creaes an instance of

classclass7-22

Page 23: Introduction to Object-oriented Programming

Defining Member Defining Member FunctionsFunctions

Member functions are part of a class Member functions are part of a class declarationdeclaration

Can place entire function definition Can place entire function definition inside the class declaration (inline inside the class declaration (inline function)function)oror

Can place just the prototype inside Can place just the prototype inside the class declaration and write the the class declaration and write the function definition after the classfunction definition after the class

7-23

Page 24: Introduction to Object-oriented Programming

Inline FunctionsInline Functions Member functions defined inside the class Member functions defined inside the class

declaration are called inline functionsdeclaration are called inline functions Only very short functions should be inline functionsOnly very short functions should be inline functions class Square{class Square{

private:private: . . . . . .

public: public: double getSide(){ return side;} double getSide(){ return side;}

. . .. . .

};};

7-24

Page 25: Introduction to Object-oriented Programming

Member Functions Member Functions Defined After the Class Defined After the Class

DeclarationDeclaration Put a function prototype in the class Put a function prototype in the class

declarationdeclaration double getSide();double getSide();

In the function definition, precede function In the function definition, precede function name with class name and name with class name and scope scope resolution operator resolution operator ((::::))

double Square::getSide()double Square::getSide(){{ return side;return side;}}7-25

Page 26: Introduction to Object-oriented Programming

ConstructorsConstructors

A A constructorconstructor is a member function is a member function that is used to initialize data members of that is used to initialize data members of a classa class

Is called automatically when an object of Is called automatically when an object of the class is createdthe class is created

Must be a Must be a publicpublic member function member function

Must be named the same as the class Must be named the same as the class

Must have no return typeMust have no return type7-26

Page 27: Introduction to Object-oriented Programming

Constructors--ExamplesConstructors--Examples

class Square {private: double side;public: Square(); Square(double s); . . .};

#include “square.h”Square::Square(){ side = 0;}

Square::Square(double s){ side = s;}

Class Declaration(square.h)

Function Definitions(square.cpp)

Page 28: Introduction to Object-oriented Programming

Invoking ConstructorInvoking Constructor

#include <iostream>#include “square.h”using namespace std;

int main(){ Square sq1; // invoking 1st constructor Square sq2(5); // invoking 2nd constructor cout << “sq1 side: “ << sq1.getSide() << endl; cout << “sq2 side: “ << sq2.getSide() << endl;

return 0; }

Client Program (squareTest.cpp)

Page 29: Introduction to Object-oriented Programming

Passing Class Object Passing Class Object As Function ArgumentAs Function Argument

A class object can be passed as an A class object can be passed as an argument to a functionargument to a function

When When passed by valuepassed by value, function , function makes a local copy of object. makes a local copy of object. Original object in calling environment Original object in calling environment is unaffected by actions in functionis unaffected by actions in function

When When passed by referencepassed by reference, function , function can use ‘set’ functions to modify the can use ‘set’ functions to modify the object.object.

7-29

Page 30: Introduction to Object-oriented Programming

7-30

Notes on Passing ObjectsNotes on Passing Objects Using a Using a value parameter-value parameter--can slow -can slow

down a program and waste spacedown a program and waste space Using a Using a reference parameter --reference parameter --speeds speeds

up program, but allows the function to up program, but allows the function to modify data in the structuremodify data in the structure

To save space and time, while protecting To save space and time, while protecting structure data that should not be structure data that should not be changed, use a changed, use a constconst reference reference parameterparameter

void showData(const Square &s)void showData(const Square &s) // header// header

Page 31: Introduction to Object-oriented Programming

Include GuardsInclude Guards Used to prevent a header file from being included twiceUsed to prevent a header file from being included twice Format:Format:

#ifndef #ifndef symbol_namesymbol_name

#define #define symbol_namesymbol_name

. . . . . . (normal contents of header file)(normal contents of header file)

#endif#endif

symbol_namesymbol_name is usually the name of the header file, in is usually the name of the header file, in all capital letters:all capital letters:

#ifndef SQUARE_H#ifndef SQUARE_H

#define SQUARE_H#define SQUARE_H

. . .. . .

#endif#endif

7-31

Page 32: Introduction to Object-oriented Programming

Array of Class ObjectsArray of Class Objects

Class objects can also be used as array elementsClass objects can also be used as array elements class Squareclass Square{ private:{ private: int side;int side; public:public: Square(int s = 1)Square(int s = 1) { side = s; }{ side = s; } int getSide()int getSide() { return side; }{ return side; }};};Square shapes[10]; // Create array of 10Square shapes[10]; // Create array of 10 // Square objects// Square objects

8-32

Page 33: Introduction to Object-oriented Programming

Arrays of Class Objects Arrays of Class Objects (cont.)(cont.)

Use an array subscript to access a Use an array subscript to access a specific object in the arrayspecific object in the array

Then use dot operator to access Then use dot operator to access member methods of that objectmember methods of that object

for (i = 0; i < 10; i++)for (i = 0; i < 10; i++) cout << shapes[i].getSide() << cout << shapes[i].getSide() << endl;endl;

8-33