0% found this document useful (0 votes)
20 views

Lec07 (Topic 4 Define Classes)

The document discusses object-oriented programming concepts including defining classes, procedural programming versus OOP, what objects and classes are, categorizing objects, object behaviors, unified modeling language and class diagrams, and the principles of abstraction, encapsulation, inheritance, and polymorphism in OOP.

Uploaded by

huaiencheeng
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Lec07 (Topic 4 Define Classes)

The document discusses object-oriented programming concepts including defining classes, procedural programming versus OOP, what objects and classes are, categorizing objects, object behaviors, unified modeling language and class diagrams, and the principles of abstraction, encapsulation, inheritance, and polymorphism in OOP.

Uploaded by

huaiencheeng
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 45

1

LECTURE 7
Defining Classes (Part 1)
2

Procedural Programming
• Procedural Programming is associated with top-down design.

• In top-down design, a problem is associated with a procedures (function in


C++).

• The idea is to design a program to solve a problem by concentrating on the


procedures first and data second.

• C and Pascal are examples of procedural programming languages.

Main Program
Data
Main program coordinates calls
to procedures and hands over
appropriate data as parameters.
Procedure 1 Procedure 2 Procedure 3
3

Problems with Procedural Programming


• Unrestricted access to global data and
procedures.

• Poor modeling of the real world (data and


procedures are separated).
• Not the way that humans naturally think
about a situation.

• Poor code reusability.


4

Why Object-Oriented Programming?


• Solution to problems of procedural programming.

• Restrict access to data and procedures (through access privilege, discussed


later).

• Better modeling of real world objects.


• Data and procedures are combined in a single unit.
• Easier to understand, correct and modify.

• Better code reusability: existing objects can be reused to create new


objects through inheritance.

• Useful for development of large and complex systems.

• The idea is to design a program to solve a problem by combining both the data
and procedures (member functions) that operate on that data into a singe unit
called object.
• C++ and Java are examples of OOP languages.
5

Object-Oriented Programming
• In OOP, object's methods (member functions) provide the only way to access its
data.

• The data can be set hidden inside an object, and therefore safe from direct
alteration from outside the class.

• To access or modify an object's data, we need to know exactly what methods


interact with it.

• Calling an object's methods is referred to as sending a message to the object.

• Objects interact by sending messages to each other.


6

What is an “Object”?
• An object is a computer representation of real-world person, place,
event or thing.
7

What is an “Object”?
• An object can be characterized by a set of attributes, and a set of behaviors that
act upon those attributes.

• An object consists of:


• attributes/data/states/variables (typically noun), and
• behaviors/procedures/methods/operations/functions (typically verb).

• We refer to a group of similar objects (with the same attributes and behaviors) as a
class.
8

What is an “Object”?

Example: Class
Object/Class: Student
Attributes: Student
1. Name Attributes
2. Student ID 1. name
3. Courses
2. student_ID
Behaviors/Methods:

4. Do homework Methods
5. Register course 1. do_homework()
6. Withdraw …
9

Object and Classes


Class: Student
10

Categorizing Objects
• The two most common ways for us to categorize objects are:

• Categorize similar objects (e.g. all cars, all students)

• Categorize objects by composition (e.g. a car is composed of an engine, four


wheels)
11

Categorizing Similar Objects


• When we categorize similar objects, we group together objects that have the
same attributes and behaviors.

• For example, we might group together in the category “car” those objects that
have same:
• Attributes (color, speed, model, etc), and
• Behaviors (drive, stop, and turn)

• We refer to a group of similar objects (with the same attributes and behaviors)
as a class.

• Thus, we can define a class as:


• “a set of objects comprised of the same attributes and behaviors”.

• Thus, we can define object as “a particular instance of a class”.

• Example "objects": car, racing car, tank, tricycle


• Each object is an instance of class motor.
12

Categorizing Similar Objects


Each of us is an instance (object) of the class human.

Class: human

Siva Ahmad Ken Hai Michael

Object A Object B Object C Object D


13

Categorizing by Composition
• When categorizing objects by composition, an attribute of a particular class is a
class by itself.

• This type of relationship is often referred to as a “has-a” relationship.

• E.g., “a car has an engine”.

Personnel Dept.
Personnel Data

Sales Dept. Personnel Finance Dept.


Staff
Sales Data Finance Data

Sales Messages Finance


Staff Staff

• 3 classes can be identified: Dept, Staff, Data


• A Dept has Staff and Data
14

Object Behaviors
• Categories of behaviors that an object can have:

1. Constructors – Specify how a new instance of a class is created.


(Create object)

2. Queries – Determine (find out) the current value of an attribute


of a particular object. (Get functions)

3. Updates – Alter the value of an attribute of a particular object.


(Set functions)

4. Destructors – Specify how an object is destroyed. (Destroy


object)
15

Object Behaviors
• For the Car class, we have identified 3 behaviors: drive, stop and turn.

• All 3 behaviors are of Update behaviors as they change the attributes


speed, and direction (not listed)

• What is the possible Queries behavior for Car class?

• If attribute speed is set hidden in the class, then a new method/behavior


has to be added in order to for others to find out the speed.

• The name of methods for getting the attributes is typically getAttribute.


getSpeed in the Car case
16

Unified Modeling Language


• A model is a representation of an actual thing/object.

• UML is a formal notation to describe models.

• Class diagram is one type of UML diagrams.

• Class diagrams are widely used to describe the types of objects in a system and
their relationships.
17

Class Diagram
Class diagram contains the following elements:

• Classes represent entities with common attributes, operations, and


associations.

• Associations represent relationships that relate two or more other classes.


18

Class Diagram
• The name of the class appears in the
top section.
Car
• The attributes in the middle section. Class
model
• The behaviors in the bottom section.
Attributes color
speed
• Note that the class diagram here is
incomplete as it does not state access
privilege of the members (discuss Behaviors drive()
later) stop()
turn()
19

Class Diagram

Car Wheel
Association model
model
color width
speed
1 n
wheel
change ()
drive ()
stop () More than 1
turn ()

Associations shows the relationship between instances of classes, e.g. a car


has more than one wheels.
20

4 Principles of OOP

1. Abstraction – focus only on information important to the problem.

2. Encapsulation – combine data and operations in a single unit, and hide


the implementation from user.

3. Inheritance - create new classes from existing classes.

4. Polymorphism – the ability to use the same expression to denote different


operations.
21

Abstraction VS Encapsulation
22

Abstraction in C++
• Abstraction is the process of separating the logical properties from the
implementation details.

• Logical properties are the information important to the problem.

• E.g. driving is a logical property of a car; the construction of the engine


constitutes the implementation details.

• We have an abstract view of what the engine does, but are not interested in
the engine’s actual details implementation.

• The notions of abstraction simplifies modeling and working on the


problem.
23

Declaring a class in C++


• Recall that a class of objects is a group of objects that have a set
of:
1. attributes/data/variables/states, and
2. behaviors/methods/functions/operations.

• In C++, object classes are created using the class data type.

The class diagram for the Car class Class


is as below: Car name

The first step is to define a new class for our


car:
attributes
class Car {

}; methods
24

Declaring a class in C++


• Next, add the attributes (data member) which we have defined for a car.

• For the car object class, we define that


• model and color are of type string, and
• speed is an int.

Car

- model:string
class Car { - color:string
string model; - speed:int
string color;
int speed;
};
25

Encapsulation

• Encapsulation is the idea that the internal workings of an object can be


hidden from the outside world.

• Encapsulation is performed in two ways:


We encapsulate the details of how attributes are stored.
We encapsulate the details of how methods are performed.

• Why would we want to encapsulate objects?

• To reduce the need for outside users to worry about how something is done.

• This provides significant benefits in program maintenance – we can change


those details without the users ever being aware (provided that the outside
interface remains the same).
26

Encapsulation

• Encapsulation is embodied in C++ class’s by restricting access


to an object’s members.

• This is accomplished by a set of keywords used to describe access


privileges:
• private
• public
• protected
• friend

• We will discuss the first two categories of access privileges now,


and leave the other two for later.
27

Encapsulation in C++
private :
• If a class’s members are declared as private, then they are not
accessible to anything except for the object itself.

• Thus, the only place where the scope of a private member would be
valid is within the object’s behaviors.

• By default, all members of a C++ class are declared as private.

• In Class Diagram, we use symbol minus "-" to denote that a member


is private
28

Encapsulation in C++
public:
• Members that are declared as public are the exact opposite –they are
fully accessible to the outside world.

• Any public member can be accessed by any other C++ object (assuming
that the scope is valid).

• In Class Diagram, we use symbol plus "+" to denote that a member is


public
29

Encapsulation in C++
• If we leave the class declaration as it is, all of the members will be private
(default).
class Car {
class Car { private:
string model; string model;
Same
string color; string color;
int speed; int speed;
}; };

• If we want all of the members to be public, then we must use the public
keyword.
class Car {
public:
string model; All public
string color;
int speed;
};
30

Encapsulation in C++
• We can “mix-and-match” keywords in order to obtain different combinations.

class Car {
class Car { public:
string model; public string model;
public: string color;
string color; private:
int speed; int speed;
}; };
31

C++ Method Declaration


• Object behaviors are implemented in C++ using methods.

• A method (or member function) is a function that is defined within a class.

• Instances of an object class can execute all of the methods that their class
defines.

• Just as with any function, the first step in writing a method is to determine
it’s interface/header.

• The interface is simply the name of the method, the parameters it requires,
and its return value.
C++ Method Declaration
• Consider the car class’s first behavior: drive.

• For argument’s sake, let’s assume that it takes as parameters two integers,
speed and distance, and returns nothing.

• The corresponding method’s interface would then be:


void drive(int speed, int distance)

Car
- Model:string
- Color:string
- Speed:int

+ drive (speed:int, distance:int): void

32
33

C++ Method Declaration


• The method interface (or method declaration) is always placed inside of the
class declaration, just as the member declarations are.

• The implementations (method definitions), however, can either be included


within the class declaration, OR placed outside of it
Outside of class
class Car
Inside of class
{
class Car void drive (int speed,
{ int distance);
void drive (int speed, };
int distance)
{ void Car::drive (int speed,
//Place definition here int distance)
} {
}; //Place definition here
}
34

C++ Method Declaration


• We will, in general, choose to separate the method declarations from their
implementations (definitions), as this separation provides the two key benefits of
encapsulation:

• Users do not have to worry about the details (consider how long and
difficult-to-read if a class declaration includes 20 methods, each with
definitions hundreds of lines long).

• Separating allows us to change the implementation details without affecting


users (provided the interfaces remain the same).

• A class’s methods have access privileges in the same way that attributes do.

• They can be declared as public, private, protected, or friend methods.

• Which keyword should we use?

• In general, we declare methods using the public keyword (otherwise we have no


way to communicate with the object).
35

C++ Method Declaration


• For the Car class, we can add the declaration for drive( ) as below:

• We may place the method declaration above the member declarations.

class Car
{ Car
public:
void drive (int speed,
- Model:string
int distance);
- Color:string
void stop( );
void turn( );
- Speed:int
private:
string model; + drive (speed:int, distance:int): void
string color; + stop (): void
int speed; + turn (): void
};
36

Commenting
• It is becoming a convention to place a comment at each declaration
(member or method) to describe its purpose.

• For data members, describe what the member represents and any
restrictions that exist on its value(s)

string color; // The color of the car


37

Commenting
• For data methods, describe what the method does, what parameters (if any)
it takes, and what its possible return values (if any) are.

• Parameters should be described in the same way that data members are.

// Method: drive
// Causes the car to drive forward at the specified speed
// for the specified distance.
//
// Parameters:
// speed – the speed of the car (in miles per hour)
// distance – the distance that the car should go (in miles)
//
// Return value:
// Returns 0 if successful, -1 otherwise.

void drive (int speed, int distance);


38

Placing class Declarations


// car.h (header file)
• In keeping with the idea of encapsulation,
#ifndef CAR_H
we will generally place the class
declaration in a C++ header file (with the #define CAR_H
name of the class). class Car {
public:
• For example, we would place the void drive (int speed,
declaration for the car class in a header file int distance);
names “car.h”.
void stop( );
• The implementation (method definition) is void turn( );
then placed in the corresponding source private:
file, “car.cpp”, or “car.cc”. string model;
string color;
int speed;
};
#endif
39

Placing class Declarations


• The previous slide includes a set of preprocessor directives - the
#ifndef/ #define/ #endif directives.

• We use #define to declare a name:


#define CAR_H // Defines the name "CAR_H“

• By convention, we use the name of the header file with an underscore (‘_’) in place
of the period.
Car class => CAR_H

• This gives us pretty good odds that we won’t accidentally use a name that already
exists.

• To prevent multiple declarations, we use the #ifndef “if-not-defined”


(#endif) directives to form a preprocessor “block” around the header code
(similar in nature to an if statement).

• The first time the header file is included, the name is not defined and the compiler
enters the block, defining the name and parsing and compiling the header code.
40

Define class Methods


• We’ve already said that the method definitions should be placed in a source
file with the same name as the class, but let’s look at how that is done.

• In the source file, you must include the header file containing the class
declaration.

• Thus, our initial “car.cpp” file might look something like this:

// car.cpp (source file)


#include <iostream>
#include "car.h" // include class declaration
using namespace std;
...
41

Define class Methods


• To include a method implementation, the scope resolution operator (::) must be
used (so that the compiler knows that we are defining a class’s method as
opposed to a brand new function).

• Thus, to define our method drive( ) for the car class, we would use the
following structure:

scope resolution operator


class name method name
void Car::drive(int speed, int distance) {
// Method definition
}
42

Define class Methods


Thus, the complete structure of the definition for class car methods might look
like this:

// car.cpp (source file)


#include <iostream>
#include "car.h" // Include class declaration
using namespace std;
void Car::drive (int speed, int distance) {…}
void Car::stop () {…}
void Car::turn () {…}
43

Scope and Methods


• Data members of a class have class scope.

• Thus, any data member of a particular class can be accessed from within
that class’s methods.

class Foo {
public: void Foo::bar() {
void bar(); x = 5;
private: };
int x; // data member
};
x here is data member
44

Scope and Methods


• If a local variable in a method or function parameter has the same name as
data member, it “overrides” data member.

class Foo { void Foo::bar() {


public: int x; // local variable
void bar(); x = 5;
void bar(int x); };
private:
int x; //data member x here is local variable x, not
}; data member x

void Foo::bar (int x) { x here is function parameter


x = 5; x, not data member x
};
45

The this Pointer


In previous case, to access data member instead of local variable or function
parameter, use this pointer or scope resolution operator (::)
this pointer is a pointer to current instance of the class

void Foo::bar( )
{
int x;
x = 5; // Sets local variable x to 5
this -> x = 5; // Sets the member Foo::x to 5
Foo::x = 5; // Same result as previous line
};

You might also like