Você está na página 1de 40

CIS1400 Programming Logic and

Technique
Topic 10 Object Oriented Programming

Chapter Topics
14.1 Procedural and Object-Oriented Programming
14.2 Classes
14.3 Using the Unified Modeling Language to Design
Classes
14.4 Finding the Classes and Their Responsibilities in a
Problem
14.5 Inheritance
14.6 Polymorphism

CIS1400 Programming Logic and Technique

10 -- Object Oriented Programming

14.1 Procedural and Object-Oriented


Programming
OOP
Fundamentals

Procedural Programming

An early method of coding where programs are centered on the


procedures or actions that take place in a program
A procedure is simply a module
As programs get larger and more complex, this method leads to
problems

Object Oriented Programming (OOP)

A newer method of coding where programs are centered on creating


objects
An object is a software entity that contains both data and procedures
The data in a object is known as the objects fields (variables,
arrays)
The procedures that are performed are called methods

CIS1400 Programming Logic and Technique

10 -- Object Oriented Programming

14.1 Procedural and Object-Oriented


Programming
OOP addresses the procedural problem of code/data
separation by using two methods

Encapsulation refers to the combining of data and code into


a single object (creating a class)
Data hiding refers to an objects ability to hide its data from
code that is outside the object

Interface versus Implementation

Another OOP benefit is Object Reusability

For example, an object that renders


3D images can be used in many different
programs

Write and test once, use many times


Consistent look and feel
File Open, Save As
CIS1400 Programming Logic and Technique

10 -- Object Oriented Programming

14.1 Procedural and Object-Oriented


Programming
An everyday example of an object
Alarm Clock

Fields (private)

current second
current minute
current hour
alarm set time
alarm set

can access

Methods (private)
increment the current second
increment the current minute
increment the current hour
sound alarm

Methods (public)

OOP
Fundamentals

set time
set alarm time
turn alarm on
turn alarm off

can access

CIS1400 Programming Logic and Technique

10 -- Object Oriented Programming

14.2 Classes

OOP
Fundamentals

OOP paradigm is made possible through the


implementation of classes in the programming language
A class is code that specifies the fields and methods for a
particular type of object

A class is coded and contains methods and fields

An object is then created from the class

Think of it like a blueprint, such as a blueprint for a house


It is a detailed description
It is an instance of a class
Think of it as the actual house
Multiple instances can be created
from a single class
will differ in their field values
CIS1400 Programming Logic and Technique

10 -- Object Oriented Programming

14.2 Classes
Creating a class type

Class ClassName
//Field declarations and method declarations
Private DataType VarName
Public Module ModuleName(DataType ParmName)
// body of module
End Module
Public Function ReturnType FuncName(DataType ParmName)
// body of function with return statement
End Function
End Class

fields
and
methods

The first line starts with Class, followed by the name of the class

name of class type

The programmer names the class following the same rules as naming
variables

The field declarations (variables) and methods are defined within the
class
CIS1400 Programming Logic and Technique

10 -- Object Oriented Programming

14.2 Classes
Access specifiers

Private allows class members to be hidden from code


outside the class

Public allows for all parts of the code to access the class
members

Internal implementation

External Interface

It is common practice to make all fields private and to provide


access only to those field through methods
Therefore, the methods should be public

CIS1400 Programming Logic and Technique

10 -- Object Oriented Programming

14.2 Classes
class type

variable name

Creating a class variable


Declare ClassName VariableName

Creating an object and assigning its address to a class


variable
Set VariableName = New ClassName()

memory address
is assigned to
VariableName
9

CIS1400 Programming Logic and Technique

creating an object
in memory using
the ClassName
class as the
blueprint
10 -- Object Oriented Programming

14.2 Classes
Inside Class Listing 14-3

10

The fields are defined as


private to ensure data
hiding
The methods are public so
they can be accessed by
main
When the set modules are
called, an argument is
passed and that value is set
to the private field
setters or mutators
modules
When the get modules are
called, they simply return
the value of the private field
getters or accessors
functions
CIS1400 Programming Logic and Technique

10 -- Object Oriented Programming

14.2 Classes
Inside Program 14-1
Creating a class variable
Creating an object and
assigning it to class
variable
Using mutators to set
field values
Using accessors to
display field values
Dot notation (.) used to
associate instance with
class member

11

CIS1400 Programming Logic and Technique

10 -- Object Oriented Programming

14.2 Classes
Constructor is a method that is automatically called when
an object is created

The purpose is to initialize an objects fields with starting


values
A programmer can write their own constructor to initialize
fields
In many programming languages, a constructor has the same
name as the class

12

Can accept arguments to initialize field values

Or they can use the default constructor that is available with


most programming languages

CIS1400 Programming Logic and Technique

10 -- Object Oriented Programming

14.2 Classes
Class Listing 14-4
Class CellPhone
// fields
Private String manufacturer
Private String modelNumber
Private Real retailPrice
// constructor
Public Module CellPhone(String manufact, String modNum,
Real retail)
Set manufacturer = manufact
Set modelNumber = modNum
Set retailPrice = retail
End Module

13

CIS1400 Programming Logic and Technique

10 -- Object Oriented Programming

14.2 Classes
Class Listing 14-4 (contd)
// mutator methods
Public Module setManufacturer(String manufac)
Set manufacturer = manufact
End Module
Public Module setModelNumber(String modNum)
Set modelNumber = modNum
End Module
Public Module setRetailPrice(Real retail)
Set retailPrice = retail
End Module
14

CIS1400 Programming Logic and Technique

10 -- Object Oriented Programming

14.2 Classes
Class Listing 14-4 (contd)
// accessor functions
Public Function String getManufacturer()
Return manufacturer
End Function
Public Function String getModelNumber()
Return modelNumber
End Function
Public Function Real getRetailPrice()
Return retailPrice
End Function
End Class
15

CIS1400 Programming Logic and Technique

10 -- Object Oriented Programming

14.2 Classes
Program14-2
Module main()
Declare CellPhone myPhone
Set myPhone = New CellPhone(Motorola, M1000, 199.99)
Display The manufacturer is , myPhone.getManufacturer()
Display The model number is , myPhone.getModelNumber()
Display The retail price is , myPhone.getRetailPrice()
End Module

ProgramOutput
The manufacturer is Motorola
The model number is M1000
The retail price is 199.99

16

CIS1400 Programming Logic and Technique

10 -- Object Oriented Programming

14.3 Using the Unified Modeling


Language to Design Classes

OOP
Fundamentals

The Unified Modeling Language (UML) is a standard way of


drawing diagrams that describe object-oriented systems

Contains a set of standard diagrams for graphically depicting


OO systems

Figure 14-10 General


layout of a UML diagram
for a class

17

CIS1400 Programming Logic and Technique

10 -- Object Oriented Programming

14.3 Using the Unified Modeling


Language to Design Classes
Data type, method parameter, and access specification
notation is also added to a UML diagram
The data type specifies the data type of the field or the data
type of the method

// field
// accessor method

The method parameter specifies the parameter variables


and their data types

setManufacturer(manufact : String)

// mutator method

The access specification indicates a + for public or a for


private

18

manufacturer : String
getRetailPrice() : Real

- manufacturer : String
+ setManufacturer(manufact : String)
CIS1400 Programming Logic and Technique

// private field
// public method
10 -- Object Oriented Programming

14.3 Using the Unified Modeling


Language to Design Classes

Figure 14-13 UML diagram


for the CellPhone class
with access specification
notation

Visio Example
19

CIS1400 Programming Logic and Technique

10 -- Object Oriented Programming

14.4 Finding the Classes and Their


Responsibilities in a Problem
First step in designing OOP is to determine:

OOP
Fundamentals

Classes
Class responsibilities

Determining classes:
Write description of problem domain

Physical objects
Identified roles
Results of an event
Recordkeeping items
In The
Spotlight
(p539)

20

Joes Automotive Shop


Services foreign cars, and specializes in servicing cars
made by Mercedes, Porsche, and BMW. When a
customer brings a car to the shop, the manager gets
the customers name, address, and telephone
number. The manager then determines the make,
model, and year of the car, and gives the customer a
service quote. The service quote shows the
estimated parts charges, estimated labor charges,
sales tax, and total estimated charges.

CIS1400 Programming Logic and Technique

10 -- Object Oriented Programming

14.4 Finding the Classes and Their


Responsibilities in a Problem
First step in designing OOP is to determine:
Classes
Class responsibilities

Determining classes:
Identify nouns

21

Consolidate similar nouns


Include only necessary nouns
Differentiate between objects
and classes
Make a distinction between
single or grouped values

Joes Automotive Shop


Services foreign cars, and specializes in servicing
cars made by Mercedes, Porsche, and BMW.
When a customer brings a car to the shop, the
manager gets the customers name, address, and
telephone number. The manager then determines
the make, model, and year of the car, and gives the
customer a service quote. The service quote
shows the estimated parts charges, estimated labor
charges, sales tax, and total estimated charges.

CIS1400 Programming Logic and Technique

10 -- Object Oriented Programming

14.4 Finding the Classes and Their


Responsibilities in a Problem
Joes Automotive Shop
Services foreign cars, and specializes in servicing cars made by Mercedes, Porsche,
and BMW. When a customer brings a car to the shop, the manager gets the
customers name, address, and telephone number. The manager then determines the
make, model, and year of the car, and gives the customer a service quote. The
service quote shows the estimated parts charges, estimated labor charges, sales tax,
and total estimated charges.

Customer

Car

ServiceQuote

- name:String
- address:String
- phone:String

- make:String
- model:String
- year:Integer

- partsCharges:Real
- laborCharges:Real

+ Customer(n:String,
a:String, p:String)
+ setName(n:String)
+ setAddress(a:String)
+ setPhone(p:String)
+ getName():String
+ getAddress():String
+ getPhone():String

+ Car(carMake:String,
carModel:String,
carYear:Integer)
+ setMake(m:String)
+ setModel(m:String)
+ setYear(y:Integer)
+ getMake():String
+ getModel():String
+ getYear():Integer

+ ServiceQuote(pc:Real, lc:Real)
+ setPartsCharge(pc:Real)
+ setLaborCharge(lc:Real)
+ getPartsCharge():Real
+ getLaborCharge():Real
+ getSalesTax(taxRate:Real):Real
+ getTotalCharge():Real

22

CIS1400 Programming Logic and Technique

10 -- Object Oriented Programming

14.4 Finding the Classes and Their


Responsibilities in a Problem
First step in designing OOP is to determine:
Classes
Class responsibilities

fields

Determining class responsibilities:


Identify things that class is responsible for knowing
Identify actions that class is responsible for doing

methods

Avoid Stale Data


Value dependent upon other data
Include function that returns result of calculation based
upon changed data

23

totalCharge = partsCharge + laborCharges + getSalesTax(taxRate)


CIS1400 Programming Logic and Technique

10 -- Object Oriented Programming

14.5 Inheritance

OOP
Fundamentals

Inheritance allows a new class to extend an existing class,


whereas the new class inherits the members of the
class it extends
The superclass is the base class
The subclass(es) is the derived class
Specialized object has all characteristics of generalized
object

is-a relationship

Figure 14-17 Bumblebees and


grasshoppers are specialized
versions of a generalized
insect
24

superclass

subclass

CIS1400 Programming Logic and Technique

10 -- Object Oriented Programming

14.5 Inheritance
Class Listing 14-8

Course Grader
The department grading scale is based on the
standard 90/80/70/60 points for A/B/C/D/F grades.

Class GradedActivity
Private Real score
GradedActivity
Public Module setScore(Real s)

- score: Real

Set score = s
End Module
Public Function Real getScore()
Return score

+ setScore(s : Real)
+ getScore() : Real
+ getGrade() : String

End Function

25

CIS1400 Programming Logic and Technique

10 -- Object Oriented Programming

14.5 Inheritance
Class Listing 14-8 (contd)
Public Function String getGrade()
Declare String grade

GradedActivity

If score >= 90 Then


Set grade = A

- score: Real

Else If score >= 80 Then


Set grade = B
Else If score >= 70 Then
Set grade = C

+ setScore(s : Real)
+ getScore() : Real
+ getGrade() : String

Else If score >= 60 Then


Set grade = D
Else
Set grade = F
End If
Return grade
End Function
End Class
26

CIS1400 Programming Logic and Technique

10 -- Object Oriented Programming

14.5 Inheritance
Program 14-4
Module main()
Declare Real testScore
Declare GradedActivity test
Set test = new GradedActivity()
Display Enter a numeric test score.
Input testScore
test.setScore(testScore)
Display The grade for that test is , test.getGrade()
End Module

Output
Enter a numeric test score.

89 [Enter]
The grade for that test is B
27

CIS1400 Programming Logic and Technique

10 -- Object Oriented Programming

14.5 Inheritance

GradedActivity
- score: Real

Course Grader
The department grading scale is based on the
standard 90/80/70/60 points for A/B/C/D/F grades.
The Final Exams are worth a maximum of 100
points but can have any number of questions; each
question is equally weighted.

Class Listing 14-9

+ setScore(s : Real)
+ getScore() : Real
+ getGrade() : String

is-a
FinalExam

Class FinalExam Extends GradedActivity


Private Integer numQuestions
Private Real pointsEach
Private Integer numMissed

28

CIS1400 Programming Logic and Technique

- numQuestions : Integer
- pointsEach : Real
- numMissed : Integer
+ FinalExam(questions :
Integer, missed :
Integer)
+ getPointsEach() : Real
+ getNumMissed() :
Integer
10 -- Object Oriented Programming

14.5 Inheritance

Class Listing 14-9 (contd)

FinalExam
- numQuestions : Integer
- pointsEach : Real
- numMissed : Integer
+ FinalExam(questions :
Integer, missed :
Integer)
+ getPointsEach() : Real
+ getNumMissed() :
Integer

Public Module FinalExam(Integer questions, Integer missed)


Declare Real numericScore
Set numQuestions = questions
Set numMissed = missed
Set pointsEach = 100.0 / questions
Set numericScore = 100 (missed * pointsEach)
Call setScore(numericScore)
End Module
29

CIS1400 Programming Logic and Technique

10 -- Object Oriented Programming

14.5 Inheritance
Class Listing 14-9 (contd)
FinalExam
Public Function Real getPointsEach()
Return pointsEach
End Function
Public Function Integer getNumMissed()
Return numMissed
End Function
End Class

30

CIS1400 Programming Logic and Technique

- numQuestions : Integer
- pointsEach : Real
- numMissed : Integer
+ FinalExam(questions :
Integer, missed :
Integer)
+ getPointsEach() : Real
+ getNumMissed() :
Integer

10 -- Object Oriented Programming

14.5 Inheritance

GradedActivity

Program 14-5

- score: Real

Module main()
+ setScore(s : Real)
+ getScore() : Real
+ getGrade() : String

Declare Integer questions, missed


Declare FinalExam exam
Display Enter the number of questions
on the exam.
Input questions

is-a

Display Enter the number of questions


that the student missed.

FinalExam

Input missed
- numQuestions : Integer
- pointsEach : Real
- numMissed : Integer

Set exam = new FinalExam(questions, missed)


Display Each question on the exam counts ,
exam.getPointsEach(), points.
Display The exam score is , exam.getScore()
Display The exam grade is , exam.getGrade()
End Module
31

CIS1400 Programming Logic and Technique

+ FinalExam(questions :
Integer, missed :
Integer)
+ getPointsEach() : Real
+ getNumMissed() :
Integer

10 -- Object Oriented Programming

14.5 Inheritance

GradedActivity

Program 14-5 (contd)

- score: Real

Output

+ setScore(s : Real)
+ getScore() : Real
+ getGrade() : String

Enter the number of questions on the exam.

50 [Enter]
Enter the number of questions that the student missed.

5 [Enter]
Each question on the exam counts 2 points

is-a
FinalExam

The exam score is 90


The exam grade is A

- numQuestions : Integer
- pointsEach : Real
- numMissed : Integer
+ FinalExam(questions :
Integer, missed :
Integer)
+ getPointsEach() : Real
+ getNumMissed() :
Integer

32

CIS1400 Programming Logic and Technique

10 -- Object Oriented Programming

14.6 Polymorphism

OOP
Fundamentals

Polymorphism allows you to create methods with the same


name in different classes (that are related through
inheritance
The programmer has the ability to call the correct method
depending on the type of object that is used to call it

Polymorphism is achieved through


Definition of method in superclass
(Re)Definition of same method in subclass

Declare variable of superclass type

33

Overrides superclass method


Can refer to objects of type superclass or subclass

CIS1400 Programming Logic and Technique

10 -- Object Oriented Programming

14.6 Polymorphism

Graded Activity
- score: Real

Course Grader
The department grading scale is based on the standard
90/80/70/60 points for A/B/C/D/F grades. Lab
assignments have a maximum value of 10 points and
use the department grading scale. The Final Exams are
worth a maximum of 100 points but can have any
number of questions; each question is equally weighted.
The Final Exam is more selective with the grading scale
and uses 95/85/75/65 points for A/B/C/D/F grades.

+ setScore(s : Real)
+ getScore() : Real
+ getGrade() : String

is-a

is-a

LabAssign

FinalExam
- numQuestions : Integer
- pointsEach : Real
- numMissed : Integer

+ LabAssign(points : Real)

34

CIS1400 Programming Logic and Technique

+ FinalExam(questions :
Integer, missed :
Integer)
+ getPointsEach() : Real
+ getNumMissed() :
Integer
+getGrade() : String

10 -- Object Oriented Programming

14.6 Polymorphism
Graded Activity
- score: Real

Class LabAssign Extends GradedActivity


Public Module LabAssign(Real points)
setScore(points * 10)
End Module

+ setScore(s : Real)
+ getScore() : Real
+ getGrade() : String

is-a

End Class

LabAssign

+ LabAssign(points : Real)

35

CIS1400 Programming Logic and Technique

10 -- Object Oriented Programming

14.6 Polymorphism
Class FinalExam Extends GradedActivity

Graded Activity

. . .
Public Function String getGrade()

- score: Real

Declare String grade


If getScore() >= 95 Then
Set grade = A

+ setScore(s : Real)
+ getScore() : Real
+ getGrade() : String

Else If getScore() >= 85 Then


Set grade = B

is-a

Else If getScore() >= 75 Then


Set grade = C
Else If getScore() >= 65 Then
Set grade = D
Else
Set grade = F
End If
Return grade
End Function

FinalExam
- numQuestions : Integer
- pointsEach : Real
- numMissed : Integer
+ FinalExam(questions :
Integer, missed :
Integer)
+ getPointsEach() : Real
+ getNumMissed() :
Integer
+getGrade() : String

End Class
36

CIS1400 Programming Logic and Technique

10 -- Object Oriented Programming

14.6 Polymorphism
Sample Program

variable of superclass can refer


to variables of subclass type

Module DisplayDetails(GradedActivity grAct)


Display Score = , grAct.getScore()
Display Grade = , grAct.getGrade()
End Module

actual method called based upon


runtime object

37

CIS1400 Programming Logic and Technique

10 -- Object Oriented Programming

14.6 Polymorphism
Sample Program
Module main()
Declare Real labScore
Declare Integer questions, missed
Declare LabAssign lab
Declare FinalExam exam
Display Enter lab score (on 10 point scale).
Input labScore
Set lab = new LabAssign(labScore)

38

CIS1400 Programming Logic and Technique

10 -- Object Oriented Programming

14.6 Polymorphism
Sample Program
Display Enter the number of questions on the exam.
Input questions
Display Enter the number of missed questions.
Input missed
Set exam = new FinalExam(questions, missed)
Display Lab Details
DisplayDetails(OOPLab)
Display Exam Details

objects of subclass type passed


as arguments

DisplayDetails(exam)
End Module

39

CIS1400 Programming Logic and Technique

10 -- Object Oriented Programming

14.6 Polymorphism
Output
Enter lab score (on 10 point scale).

9 [Enter]
Enter the number of questions on the exam.

50 [Enter]
Enter the number of questions that the student missed.

5 [Enter]
Lab Details
Score = 90
Grade = A
appropriate grading scale used
for object type
Exam Details
Score = 90
Grade = B
40

CIS1400 Programming Logic and Technique

10 -- Object Oriented Programming

Você também pode gostar