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

Object-Oriented and Event-Driven Programming: Prelude To Programming, 6Th Edition by Elizabeth Drake

This document discusses object-oriented programming and classes. It explains that an object contains both data (attributes) and processes (methods) that operate on that data. A class defines the structure of objects of that class type, including their attributes and methods. Objects are instances of a class and encapsulate specific attribute values and behaviors. The document provides examples of defining a Clock class and creating alarm_clock objects as instances of that class.

Uploaded by

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

Object-Oriented and Event-Driven Programming: Prelude To Programming, 6Th Edition by Elizabeth Drake

This document discusses object-oriented programming and classes. It explains that an object contains both data (attributes) and processes (methods) that operate on that data. A class defines the structure of objects of that class type, including their attributes and methods. Objects are instances of a class and encapsulate specific attribute values and behaviors. The document provides examples of defining a Clock class and creating alarm_clock objects as instances of that class.

Uploaded by

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

Chapter 11

Object-Oriented and
Event-Driven Programming

PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

11.1 Classes and Objects


An object is a structure composed of:
data (or a*ributes)
processes (or methods) that perform operaIons on that data.
Object-oriented programming is oKen referred to as OOP
OOP is an approach to program design and coding that emphasizes:
the objects needed to solve a given problem
and the rela8onships among them

PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

The Clock Class


The fundamental enIty in object-oriented programming is
the class.
A class is a data type that:
allows us to create objects
provides the deni8on for a collecIon of objects by:
describing its a*ributes (data)
specifying the methods (operaIons) that may be applied to
that data
PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

Classes
The alarm_clock class describes
what an alarm_clock is and
what can be done with it.
An alarm clock object
is a parIcular example of
an alarm_clock.

PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

The Class as a Data Type


A primi8ve data type is predened by the programming language.
It is named by a reserved keyword, like Integer, Float, or
Character.
A class is a data type that the programmer creates.
The purpose of dening a class is to allow us to create objects.
An object is just a parIcular instance of its class.

PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

An Instance of an Object or a Data Type


An object is just a parIcular instance of its class
The relaIonship between a class and its objects is like the relaIonship between a data type and variables of that type

Example: Declare Number As Integer


states what kind of data we are dealing with
what operaIons (+, , and so forth) can be performed on it
the variable Number is a parIcular instance of the type Integer

Dierence between a primiIve data type and a class:


programmer creates the class and denes the aYributes and methods associated with that class
a primiIve data type is dened in the programming language

PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

Objects
Objects are made up of two components:
data (aYributes)
operaIons on that data (methods)

We say that an object encapsulates data and operaIons


an object is like a liYle package containing both the data and operaIons
about that parIcular object
the operaIons are specied in the class deniIon
the data are specic to the parIcular object under consideraIon
the type of data is specied in the class deniIon

PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

The alarm_clock class and its objects


alarm_clock class:

aYributes (shape, color, display face, sound, etc.)
methods (changing volume, choosing sound, set snooze, how to turn it on and o, etc.)
We create instances of the alarm_clock class by assigning values to its aYributes and methods.

The windup_clock instance of the alarm_clock class is an object which encapsulates:
a*ributes: shape (round), color (blue), display (hours, minutes, with a second hand in a circular


display), sound (loud clangs), etc.
methods:
volume se[ngs (loud), sounds (one sound), snooze (none), on/o (manual windup), etc.
The electric_clock object, another instance of the alarm_clock class, encapsulates:
a*ributes: shape (rectangular), color (black), display (digital hours and minutes), sound (rings or radio), etc.
methods:
volume se[ngs (soK, medium, loud), sounds (beep, clang, radio), snooze (set Ime


from 5 15 minutes), on/o (electric or baYery), etc.

PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

Dening Classes and Crea?ng Objects


To use objects in a program, rst dene a class for each kind of object.
The class deniIon provides structure of objects in itaYributes they possess and methods that may be applied to them.

To dene the class Cube, we use the following pseudocode:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

Class Cube
Declare Side As Float //Side is an attribute
Declare Volume As Float //Volume is an attribute
Subprogram SetSide(NewSide) //SetSide() is a method
Set Side = NewSide
End Subprogram
Subprogram ComputeVolume() //ComputeVolume() is a method
Set Volume = Side^3
End Subprogram
Function GetVolume() As Float //GetVolume() is a method
Set GetVolume = Volume
End Function
Function GetSide() As Float //GetSide() is a method
Set GetSide = Side
End Function
End Class

PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

Access Methods
In the example on the previous slide, the methods SetSide() (line
6), GetVolume() (line 10), and GetSide() (line 13) are called
access methods

They provide the rest of the program with access to the objects aYributes.

SetSide() imports a value of the aYribute Side from the main


program.
GetSide() and GetVolume() allow the main program to make
use of the values of Side and Volume.

PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

Data Hiding
Why not just pass the values of the variables Side and Volume back and forth to the program as

parameters?

In OOP, normally we want to keep the class variables completely hidden from the rest of the program.
This pracIce is called data hiding and has a two-fold purpose:
1. It enhances the security of the objects data. The data cannot be altered except by using one of the
objects methods.
v For example, if you were wriIng an adventure game and had a Monster class that dened objects with one head
and a tail, you would want to be sure that any Ime you created a new Monster object, the class had not been
changed to a two-headed tailless creature because someone else had edited a Monster object elsewhere in the
program.

2. It helps to shield the inner workings of the object from the programmer. In OOP, objects work like
black boxes.

PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

Public vs Private AEributes and Methods


Can make some aYributes and methods available to code outside an object of that class while keeping other
methods and aYributes hidden.

State which members of a class are public (available to code outside the object) and which are private (not
available outside the class).
Most programming languages use the keywords Public and Private
The keyword, placed in front of the aYribute or method name, species the status of that class member
AYributes are normally declared to be Private to protect their integrity
Methods are declared as Public if they are part of the interface between the object and program
Methods are declared as Private if they are only used within the class itself
AYributes may be declared Protected if they are meant to be available (Public) to derived classes but
hidden (Private) from the rest of the program.

PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

Instan?a?on (Crea?ng an Object)


Each Ime we create an object based on a class, we say we are creaIng an instance of the

class.

We must perform an instan8a8on operaIon.


InstanIaIon is done by a declaraIon statement placed in the main program.
Example: The statements:
Declare Cube1 As New Cube
Declare Cube2 As New Cube
Create (instanIate) two objects, named Cube1 and Cube2 of the class Cube.
The keyword New species that a new object of a certain class type is being created

PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

Dot Nota?on
Once created, we can use the objects Cube1 and Cube2 in a program.
We use dot nota8on to refer to the object and method or aYribute under consideraIon.
Example: to assign a value of 10 to the Side aYribute of Cube1 use:
Call Cube1.SetSide(10)
This statement calls the method SetSide()and assigns 10 to its argument, NewSide.
To ensure that this method is se[ng the Side of the object Cube1 (not that of Cube2), place
Cube1 in front of the subprogram name, separated by a dot (period).
To display the Volume aYribute of Cube2, use the following statement:
Write Cube2.GetVolume()
In general, to refer to a public member of an object, use:
ObjectName.MemberName

PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

Using an Object in a Class


1
2
3
4
5
6
7
8
10

Main
Declare Cube1 As New Cube
Declare Side1 As Float
Write Enter the length of the side of a cube:
Input Side1
Call Cube1.SetSide(Side1)
Call Cube1.ComputeVolume()
Write Volume of a cube of side + Cube1.GetSide() +
is + Cube1.GetVolume()
End Program

PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

The Constructor
If the main program calls a subprogram before its aYributes have been given a value, an error may
occur.
To prevent this we use constructors to ini8alize an objects aYributes.
A constructor is a special method included in the class deniIon that automaIcally performs
specied setup tasks when an object is created.
The constructor will iniIalize the objects aYributes.
It establishes the condiIons that dont change.
A constructor is a special method that can be used to create objects of the class.
Constructors are automaIcally called when an object is created.
They are normally disInguished by having the same name as the class of the object they are
associated with.
The constructor is created when the class is created.

PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

Crea?ng
a Constructor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

Class Cube
Declare Private Side, Volume As Float
// The Cube constructor:
Public Cube()
Set Side = 1.0
Set Volume = 1.0
End Constructor
Public Subprogram SetSide(NewSide)
Set Side = NewSide
End Subprogram
Public Subprogram ComputeVolume()
Set Volume = Side^3
End Subprogram
Public Function GetVolume() As Float
Set GetVolume = Volume
End Function
Public Function GetSide() As Float
Set GetSide = Side
End Function
End Class

PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

11.2 More Features of Object-Oriented


Programming
Benets of Object-Oriented Languages
1.

Due to the self-contained nature of objects and the properIes of


inheritance and polymorphism OOP is beYer equipped than procedural
programming to deal with extremely complex soKware.

2.

The graphical user interface (GUI) gradually became almost universal. A GUI
comprises objects (windows, boxes, buYons, and so forth), so OOP became
the natural way to program for these interfaces.

PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

Inheritance, Encapsula?on, and


Polymorphism
A true OOP language must include the following features:
Encapsula8on: the incorporaIon of data and operaIons on that data into a
single unit in such a way that the data can only be accessed through these
operaIons. This is the fundamental idea behind classes and objects.
Inheritance: the ability to create new classes that are based on exisIng ones.
The methods (operaIons) and aYributes (data) of the original class are
incorporated into the new class, together with methods and aYributes specic
to the laYer.
Polymorphism: the ability to create methods that perform a general funcIon,
which automaIcally adapts itself to work with objects of dierent classes.

PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

Classifying objects can help explain what they


are and how they operate.
For example:
if we know what a car is, we know that all
cars have Ires, a steering wheel, brakes,
doors, and so on
if a friend tells us he has a converIble, he
doesnt have to explain the aYributes and
funcIons that it has in common with a car
a converIble inherits these aYributes and
funcIons because it is a car
if we have never seen a converIble, the
friend would only have to tell us about the
special features that disInguish it from any
car

Inheritance

This concept of classicaIon and inheritance


also works in object-oriented programming.

PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

Inheritance: Extending a Class


Object-oriented languages allow us to create subclasses of an
exisIng class.
The exisIng class is called the parent or base class.
The subclass is called the child or derived class.
The aYributes and methods of the base class automaIcally become members
of the derived class, together with any addiIonal aYributes and methods
dened specically for the laYer.

We can say that the child class extends the parent class.

PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

Class Cube
Declare Protected Side, Volume As Float
Public Cube() //create constructor
Set Side = 1.0; Set Volume = 1.0
End Constructor
Public Subprogram SetSide(Float NewSide)
Set Side = NewSide
End Subprogram
Public Subprogram ComputeVolume()
Set Volume = Side^3
End Subprogram
Public Function GetVolume() As Float
Set GetVolume = Volume
End Function
Public Function GetSide() As Float
Set GetSide = Side
End Function
End Class

Example:
A Child Class
of the Cube Class

//Create the child class


19 Class SquareBox Extends Cube
20
Declare Private Height As Float
21
Public SquareBox() //create constructor
22
Set Height = 1.0
23
Set Side = 1.0
24
Set Volume = 1.0
25
End Constructor
26
Public Subprogram SetHeight(Float NewHeight)
27
Set Height = NewHeight
28
End Subprogram
29
Public Function GetHeight() As Float
30
Set GetHeight = Height
31
End Function
32
Public Subprogram ComputeVolume()
33
Set Volume = Side^2 * Height
34
End Subprogram
35 End Class

PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

Polymorphism
In a hierarchy of classes, oKen some methods are common to
several classes, but their deniIons may dier from class to
class.
A module might contain deniIons of many three-
dimensional objects, like cubes, boxes, spheres, or cylinders.
Each of these needs a dierent formula to compute the volume.

Polymorphism allows for this kind of exibility.

PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

Example: Polymorphism and Virtual Methods


Imagine a program that is created to provide the payroll department of a certain company
with informaIon about employee paychecks.
The program contains a parent class called Worker with members that describe things
common to all employees.
It also has several child classes that contain members with informaIon specic to
dierent types of workers (such as truck drivers, clerical sta, etc.).
The Worker parent class, among other things, computes the gross pay of an employee
but dierent types of employees have paychecks calculated in dierent ways.
The following slides show, in general, how OOPs property of polymorphism can handle
this problem.


PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

Polymorphism and Virtual Methods (con?nued)


The Worker parent class computes the gross pay of an employee with a method called
ComputeGross() which uses the results of two other methods in the class:
ComputeReg() calculates regular pay: hourly rate X hours up to 40
ComputeOT() calculates overIme pay by hours over 40 X 1.5 X hourly rate
ComputeGross() uses the following formula:
Gross = ComputeReg(RegHours) + ComputeOT(OverHours)
Student workers overIme is calculated dierently:

at 1.75 X hourly rate for hours over 40
The child class, StudentWorker, can use ComputeGross() but must use its own
method for overIme pay.
ComputeGross() uses a ComputeOT() method which is in the parent class.
Must tell the parent class that, for StudentWorker objects, it must use the
ComputeOT() method from the subclass and not from its own class

PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

Polymorphism and Virtual Methods (con?nued)


Polymorphism allows us to handle this problem.
Some OOP languages can declare the ComputeOT() method in the Worker
class as a virtual method which is only accessed when instructed.

This allows StudentWorker to make use of the ComputeGross() method
in the parent class and subsItute its own ComputeOT() method for the one
dened in the parent class.

PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

11.3 Object-Oriented Program Design


and Modeling
OOP design emphasizes determining the objects needed to solve a given
problem.
In terms of the program development cycleproblem analysis, program design,
program coding, and program tesIngit is the analysis phase that diers the
most between the two approaches.
To develop an OOP program, the analysis phase entails the following:
1.
2.
3.
4.

Iden8fying the classes to be used in the program


Determining the a*ributes needed for the classes
Determining the methods needed for the classes
Determining the rela8onships among the classes

PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

Modeling Languages
Flowcharts, hierarchy charts, and IPO (Input-Process-Output charts) are
used to help design programs.
As programs get larger the models also get larger and more
complicated.
SoKware developers use modeling languages to help design large
programs.
An object modeling language is a standardized set of symbols that
includes ways to arrange these symbols to model parts of an object-
oriented soKware design or system design.

PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

Unied Modeling Language (UML)


Unied Modeling Language (UML)

a non-proprietary, general-purpose modeling language


accepted in 2000 by InternaIonal OrganizaIon for StandardizaIon (ISO)
is an industry standard for describing soKware-intensive systems
UML 2.4.1, the current version, was published in 2011 by the Object Management Group (OMG)

The term Unied Modeling Language resulted from the combined eorts of 3
men:
Ivar Jacobson, James Rumbaugh, and Grady Booch, nicknamed the Three Amigos

UML can be used to create an abstract model of a system


UML diagrams represent three dierent views of a system model
PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

Three Views of a System Model


1.The funcIonal requirements view

emphasizes the requirements of the system from users viewpoint


presents a graphical overview of what a system does, in terms of acIons and goals, and any dependencies
between them

2.The staIc structural view

emphasizes the staIc structure of the system using objects, aYributes, operaIons, and relaIonships
includes diagrams that allow the designer to see the structure of a program by showing the classes, their
aYributes, and the relaIonships between the classes
also includes diagrams that show the internal structure of a class and the relaIonships that this structure
makes possible

3.The dynamic behavior view

emphasizes the dynamic behavior of the system


shows collaboraIons among objects and changes to the internal states of objects
dynamic characterisIcs of a system are the ways the system behaves in response to certain events or acIons
PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

Categories of UML Diagrams


There are 3 signicant categories of diagrams:
Structure diagrams emphasize what things must be in the
system being modeled.
Behavior diagrams emphasize what must happen in the system
being modeled.
Interac8on diagrams are a subset of behavior diagrams; they
emphasize the ow of control and data among the things in the
system being modeled.

PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

Why Use UML?


In a well-designed OOP program, classes and subclasses have many uses.
CreaIng soKware is a maYer of wriIng enormous amounts of code
But the code can reuse many of the same classes, subclasses, and
objects in dierent ways

UML helps the designers:
keep track of what they are doing
what has been done
helps them devise ways to increase funcIonality and improve the
program through Ime
PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

11.4 Graphical User Interfaces and


Event-Driven Programming
One important applicaIon of object-oriented programming
(OOP) is to create programs that use a graphical user
interface (GUI).
A GUI includes windows that contain components such as:
vMenus
vBuYons
vBoxes

These allow users to make choices and issue commands.

PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

Window
Components

PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

Crea?ng GUI Objects in a Program


In some programming languages, GUI objects are created in the
same way as any other objects, as instances of the class to which
they belong.
In other programming languages, GUI objects are selected from a
menu or toolbar and drawn on the screen.
Each window and window component (command button,
text box, and so forth) in a GUI has a set of aYributes (or
properIes), such as name, position, and size.

PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

Some Proper?es of a window


name (by which its known in the program)
height and width (usually in pixels, the
Iny dots that make up the screen image)
title (Area Calculator shown on
right)
title font (the typeface and size of the
window Itle)
visible (true or false)whether or
not the window appears on the screen

PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

Some Proper?es of command and option buttons


Some command button properIes:
name (by which its known in the program)
caption (Done or Calculate shown in gure)
position (distance, in pixels, from the leK and top edges of window)
enabled (true or false)whether the buYon is acIve or inacIve
Some option button properIes:
name (by which its known in the program)
caption (All, Pages, or Selection shown in window slide)
enabled (true or false)whether the buYon is acIve or inacIve
value (true or false)whether or not the opIon buYon has a bullet

PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

Most GUI properIes have default values


automaIcally used unless new ones are assigned
to change these default values, use assignment statements
Example:
In the Area Calculator window, if the name of the window is MainWindow, then
use statements:
Set MainWindow.title = Area Calculator
Set MainWindow.height = 100
to specify that the title of the window is Area Calculator and the
height is 100 pixels.
If the name of the right command button is QuitButton, then the following
statements:
Set QuitButton.caption = Done
Set QuitButton.enabled = false
label the buYon as Done and cause it to be grayed out when the window is
opened.


PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

Se[ng
Proper?es

Event-Driven Programming: Handling Events


In many programs the acIons of the user (like clicking the mouse) or system-
related circumstances (like the state of a Imer) determine the ow of
execuIon.
These acIons are called events and the resulIng program is said to be event-
driven.
windows and the components contained within them are objects that have
various aYributes.
A set of events and methods, called event-handlers or event procedures are
associated with each object

PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

Some methods for windows and


Components
window
Open(): opens (displays) the window
StartUp(): a programmer-wriYen
procedure that executes automaIcally
when the window is opened
Close(): this closes the window
(removes it from the screen)

command button
Click(): executes automaIcally when the
buYon is clicked
text box
Click(): executes automaIcally when the
box is clicked
Change: executes automaIcally when the
text within the box is changed

option button
Click(): executes automaIcally when the
buYon is clicked

PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

Window
name = MainWindow
title = Area Calculator
Upper Label
text = Side of square
Lower Label
text = Area of square
Upper Text Box
name = InputBox
text =
Subprogram InputBox.Click()
Set InputBox.text =
Set OutputBox.text =
Set CalculateButton.enabled = false
End Subprogram
Subprogram InputBox.Change()
Set CalculateButton.enabled = true
End Subprogram
Lower Text Box
name = OutputBox
text =
Left Command Button
name = CalculateButton
caption = Calculate
enabled = false
Subprogram CalculateButton.Click()
Set OutputBox.text = Val(InputBox.text)^2
End Subprogram
Right Command Button
name = DoneButton
caption = Done
Subprogram DoneButton.Click()
Call MainWindow.Close
End Program
End Subprogram

PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

An Event-Driven
GUI Calculator

Event-Driven Program Design: Analysis Phase


1. IdenIfy windows needed in the program.
2. Determine relaIonships among the windows.
For example, which window can open another so that the laYer appears on the screen.
Such relaIonships can be pictured in a ow diagram (see next slide) where an arrow
poinIng from one window to another means that the rst can open or reacIvate the
second. A double arrow, poinIng in both direcIons means that either window can open
or reacIvate the other.
3. For each window do the following:
Determine the components needed for that window
Draw a rough sketch of the resulIng window
Determine the properIes and methods needed for the window and each of its
components

PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

Flow Diagram
for a
GUI Program

PRELUDE TO PROGRAMMING, 6TH EDITION BY ELIZABETH DRAKE

You might also like