Contents
Overview 1
Classes and Objects 2
Using Encapsulation 10
C# and Object Orientation 21
Lab 7.1: Creating and Using Classes 39
Defining Object-Oriented Systems 52
Review 61
Module 7: Essentials of
Object-Oriented
Programming
Information in this document, including URL and other Internet Web site references, is subject to
change without notice. Unless otherwise noted, the example companies, organizations, products,
domain names, e-mail addresses, logos, people, places, and events depicted herein are fictitious,
and no association with any real company, organization, product, domain name, e-mail address,
logo, person, places or events is intended or should be inferred. Complying with all applicable
copyright laws is the responsibility of the user. Without limiting the rights under copyright, no
part of this document may be reproduced, stored in or introduced into a retrieval system, or
transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or
otherwise), or for any purpose, without the express written permission of Microsoft Corporation.
Describe abstraction and how it helps you to create reusable classes that are
easy to maintain.
Use encapsulation to combine methods and data in a single class and
enforce abstraction.
Explain the concepts of inheritance and polymorphism.
Create and use classes in C#.
Materials and Preparation
This section provides the materials and preparation tasks that you need to teach
this module.
Required Materials
To teach this module, you need the following materials:
Microsoft
®
PowerPoint
®
file 2124C_07.ppt
Module 7, “Essentials of Object-Oriented Programming”
Lab 7, Creating and Using Classes
Preparation Tasks
To prepare for this module, you should:
Read all of the materials for this module.
is a copy good enough?
Using Encapsulation
This section provides the motivation for combining data and methods. It
provides the answer to the question, “Why encapsulate?” This section also
provides a small amount of C# syntax for creating encapsulated classes.
A top-level class cannot be declared private. It is best not to spend too much
time on top-level visibility: this topic is covered in a later module.
Nested classes are not covered in the lab exercises.
C# and Object Orientation
This section explains the terminology and concepts of object-oriented
programming.
Defining Object-Oriented Systems
The word system in this section is used to emphasize the higher-level
structure that inheritance provides. Class hierarchy design is essentially
framework design and requires thought and experience. Do not spend too
much time on detailed explanations. Remember that the primary aim of this
module is to teach the theory. In keeping with this aim, the slides use
Unified Modeling Language (UML) notation.
Be sure to read the notes in the Inheritance topic and explain why the man,
woman, and child relationship is not a good example of object-oriented
inheritance. Inheritance is misunderstood and misused in object-oriented
programming, so it is a good idea to dispel a few misunderstandings right
away.
Do not spend too much time on single and multiple inheritance at this time.
Remember, you have not yet covered interfaces.
Module 7: Essentials of Object-Oriented Programming v
-
TRAINER USE
******************************
C# is an object-oriented programming language. In this lesson, you will learn
the terminology and concepts required to create and use classes in C#.
After completing this module, you will be able to:
Define the terms object and class in the context of object-oriented
programming.
Define the three core aspects of an object: identity, state, and behavior.
Describe abstraction and how it helps you to create reusable classes that are
easy to maintain.
Use encapsulation to combine methods and data in a single class and
enforce abstraction.
Explain the concepts of inheritance and polymorphism.
Create and use classes in C#.
Topic Objective
To provide an overview of
the module topics and
objectives.
Lead-in
In this module, you will learn
more details about classes
and objects.
Topic Objective
To provide an overview of
the topics covered in this
section.
Lead-in
You will often hear the terms
class and object. In this
lesson, you will learn exactly
what these terms mean.
Module 7: Essentials of Object-Oriented Programming 3 What Is a Class?
For the philosopher…
An artifact of human classification!
Classify based on common behavior or attributes
Agree on descriptions and names of useful classes
Create vocabulary; we communicate; we think!
For the object-oriented programmer…
A named syntactic construct that describes common
behavior and attributes
A data structure that includes both data and functions
Classes are not restricted to classifying concrete objects (such as cars); they can
also be used to classify abstract concepts (such as time). However, when you
are classifying abstract concepts, the boundaries are less clear, and good design
becomes more important.
The only real requirement for a class is that it helps people communicate.
Topic Objective
To explain the concept of a
class.
Lead-in
The C# language is
primarily concerned with
defining classes and
specifying their behavior.
4 Module 7: Essentials of Object-Oriented Programming What Is an Object?
An object is an instance of a class
Objects exhibit:
Identity: Objects are distinguishable from one another
Behavior: Objects can perform tasks
State: Objects store information
*****************************
ILLEGAL FOR NON
of identity, behavior, and
state. For example, you can
ask students if this
statement refers to cars as
objects or as a class: "The
carpool lane, which is the
rightmost lane, is for cars
with more than three
passengers." This statement
uses "car" as an object—an
instance of a class. Objects
can be anonymous, but they
are still objects. The fact
that a car has three people
in it does not make it a
different sort of object from
a car that has two people in
it, or four people. In fact, the
number of people in the car
is an example of the car’s
state. Explain that state
refers to the values of the
internal attributes of an
object that might vary over
time, such as the number of
passengers. Contrast this to
values that are probably
fixed and that do not vary
after the car is created, such
as the number of doors.
Identity, inaccessible state, added behavior
struct Time class BankAccount
{ {
public int hour; ...
public int minute; ...
} }
struct Time class BankAccount
{ {
public int hour; ...
public int minute; ...
} }
*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
Structs
A struct, such as Time in the preceding code, has no identity. If you have two
Time variables both representing the time 12:30, the program will behave
exactly the same regardless of which one you use. Software entities with no
identity are called values. The built-in types described in Module 3, “Using
Value-Type Variables,” in Course 2124C, Programming with C#, such as int,
bool, decimal, and all struct types, are called value types in C#.
Variables of the struct type are allowed to contain methods, but it is
recommended that they do not. They should contain only data. However, it is
perfectly reasonable to define operators in structs. Operators are stylized
methods that do not add new behavior; they only provide a more concise syntax
for existing behavior.
Classes
Value Types and Reference Types
Value types are the types found at the lowest level of a program. They are the
elements used to build larger software entities. Value type instances can be
freely copied and exist on the stack as local variables or as attributes inside the
objects they describe.
Reference types are the types found at the higher levels of a program. They are
built from smaller software entities. Reference type instances generally cannot
be copied, and they exist on the heap.
8 Module 7: Essentials of Object-Oriented Programming Abstraction
Abstraction is selective ignorance
Decide what is important and what is not
Focus and depend on what is important
Ignore and do not depend on what is unimportant
Use encapsulation to enforce an abstraction
The purpose of abstraction is not to be vague,
but to create a new semantic level in which one can be absolutely precise.
Edsger Dijkstra
The purpose of abstraction is not to be vague,
but to create a new semantic level in which one can be absolutely precise.
Edsger Dijkstra
*****************************
To define abstraction.
Lead-in
Do you need to know how
everything works to be able
to use it?
Delivery Tip
The slide says quite a few
things. The first is that you
need to decide what is
important and what is not. In
other words, you need to
make design judgments.
Given the level of this
course, do not spend much
time on this, if you spend
any time on it at all. Instead,
focus on the dependency
aspect, which relates closely
to the idea of change (which
is covered below).
Module 7: Essentials of Object-Oriented Programming 9 Related Quotes
To illustrate the principle of minimal dependency that makes abstraction so
important, here are some related quotes:
The more perfect a machine becomes, the more they are invisible behind their
function. It seems that perfection is achieved not when there is nothing more to
add, but when there is nothing more to take away. At the climax of its
evolution, the machine conceals itself entirely.
mathematics include
computer-related
semaphores. His famous "P
and V" names for
semaphores are derived
from the Dutch words
passeer and verlaat, or pass
and leave. The Dijkstra
Algorithm, which finds the
shortest path from a point
on a graph to a destination,
is named after Dijkstra.
10 Module 7: Essentials of Object-Oriented Programming
Using Encapsulation
Combining Data and Methods
Controlling Access Visibility
Why Encapsulate?
Object Data
Using Static Data
The capsule boundary forms an inside and an outside
Withdraw( )
Deposit( )
balance
Withdraw( )
Deposit( )
balance
BankAccount ?BankAccount ?
*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
There are two important aspects to encapsulation:
Combining data and functions in a single entity (covered in the slide)
Controlling the accessibility of the entity members (covered in the next
slide)
Procedural Programming
Traditional procedural programs written in languages such as C essentially
contain a lot of data and many functions. Every function can access every piece
of data. For a small program this highly coupled approach can work, but as the
program grows larger it becomes less feasible. Changing the data representation
causes havoc. All functions that use (and hence depend upon) the changed data
fail. As the program becomes larger, making any change becomes more
difficult. The program becomes more brittle and less stable. The separate data-
in this slide because
capsule is the root word of
encapsulation.
Note that the graphic on the
left is labeled with a
question mark. This is
because there is no
individual, separate item
that represents the bank
account.
12 Module 7: Essentials of Object-Oriented Programming Object-Oriented Programming
Object-oriented programming arose to alleviate these problems. Object-oriented
programming, if understood and used wisely, is really person-oriented
programming because people naturally think and work in terms of the high-
level behavior of objects.
The first and most important step away from procedural programming and
towards object-oriented programming is to combine the data and the functions
into a single entity.
Module 7: Essentials of Object-Oriented Programming 13 Controlling Access Visibility
Methods are public, accessible from the outside
Data is private, accessible only from the inside
make the Withdraw and Deposit methods public, and the balance private.
Now the only way to increase the account balance from the outside is to deposit
some money into the account. Note that Deposit can access the balance
because Deposit is on the inside.
Topic Objective
To describe how
encapsulation can be
enforced.
Lead-in
Having decided on the
details that are going to be
hidden from the outside
world, how do you ensure
that nobody can see how
your classes work?
Delivery Tip
The slide explains the
second aspect of
encapsulation.
Note that the graphic on the
left is labeled with a
question mark. This is
because in real life you
cannot directly access your
bank balance. The graphic
on the right redraws the
boundary so that the
balance is on the inside.
Because this is how real
Allows control
Use of the object
is solely through the
public methods
Allows change
Use of the object
is unaffected if
the private data
type changes
Withdraw( )
Deposit( )
dollars 12
Withdraw( )
Deposit( )
balance 12.56
cents 56
*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
Two reasons to encapsulate are:
To control use.
modify the way in which
information is held or
processed?
Delivery Tip
The slide introduces the
concept of change and the
essence of what object-
oriented programming is all
about. You cannot prevent
change; the best you can do
is to work with a language
and a design process that
minimizes the impact of
change when it does
happen.
Note that the balance is
$12.56 in both examples on
the slide (in different
representations).
16 Module 7: Essentials of Object-Oriented Programming Object Data
Object data describes information for individual objects
For example, each bank account has its own balance. If
two accounts have the same balance, it is only a
coincidence.
Using Static Data
Static data describes information for all objects
of a class
For example, suppose all accounts share the same
interest rate. Storing the interest rate in every account
would be a bad idea. Why?
Withdraw( )
Deposit( )
balance 12.56
interest 7%
Withdraw( )
Deposit( )
balance 99.12
interest 7%
*****************************
ILLEGAL FOR NON
-
TRAINER USE
******************************
Sometimes it does not make sense to store information inside every object. For
example, if all bank accounts always share the same interest rate, then storing
the rate inside every account object would be a bad idea for the following
same class do need to
share data.
Delivery Tip
The interest rate is depicted
on the slide as object data.
The red "X" indicates that
this is a bad idea.
The second lab exercise
asks the students to create
static data and static
methods.
18 Module 7: Essentials of Object-Oriented Programming Declaring Static Data
Static data is physically declared inside a class (which is a static, compile-time
entity) and benefits from the encapsulation the class affords, but it is logically
associated with the class itself and not with each object. In other words, static
data is declared inside a class as a syntactic convenience and exists even if the
program never creates any objects of that class.
Module 7: Essentials of Object-Oriented Programming 19 Using Static Methods
Static methods can only access static data
A static method is called on the class, not the object
InterestRate( )
encapsulate static data in the same way that you can encapsulate object data.
A static method exists at the class level and is called against the class and not
against an object. This means that a static method cannot use this, the operator
that implicitly refers to the object making an object method call. In other words,
a static method cannot access non-static data or non-static methods. The only
members of a class that a static method can access are static data and other
static methods.
Topic Objective
To describe static methods.
Lead-in
If the interest rate belongs to
the account class rather
than an individual account
object, and if you are using
encapsulation to hide the
internal representation of
the interest rate, how should
the interest rate be
accessed or modified?