Windows and Web Apps in C#
Session 2
Last Update: 4/11
David Figge
[email protected]
Page 1
Copyright (C) 2009 by David Figge. All Rights Reserved.
Checkbook Register

Let’s take a look at my solution for the
Checkbook Register program…
Last Update: 4/11
Page 2
Copyright (C) 2009 by David Figge. All Rights Reserved.
Object Oriented Concepts
Windows and Web Apps in C#
Last Update: 4/11
Page 3
Copyright (C) 2009 by David Figge. All Rights Reserved.
Object Oriented Concepts

We’ve sort of danced around the
concept of objects and classes. I think
at this point it would be useful to have
an idea as to what we mean by Object
Oriented




So what is this Object Oriented stuff?
What’s the alternative?
What’s the big deal?
Let’s talk…
Last Update: 4/11
Page 4
Copyright (C) 2009 by David Figge. All Rights Reserved.
A Little History

Computers came into being about 50
years ago


Computers were good at taking a
simple task and doing it many times


The first ones were very simple
A first use was missile trajectories
Not surprisingly, code was procedural

Simple steps with loop instructions
Last Update: 4/11
Page 5
Copyright (C) 2009 by David Figge. All Rights Reserved.
A Little History

This was the typical way of
programming for the next 30 years


Through the introduction of PCs
Most programming languages used this
procedural concept

Last Update: 4/11
Assembly, BASIC, C, Forth, Pascal, RPG…
Page 6
Copyright (C) 2009 by David Figge. All Rights Reserved.
Procedural Example
10. REM Calculate power
20. INPUT “Enter base number: “, B
30. INPUT “Enter power: “, P
40. SET N=B
50. P = P – 1
60. IF P = 0 THEN 90
70. N = N * B
80. GOTO 50
90. PRINT N
100. END
Last Update: 4/11
Page 7
Copyright (C) 2009 by David Figge. All Rights Reserved.
A Little History

In the early 70’s interest started
gathering around a few OOP
languages



e.g. Smalltalk
This was largely because computers
were becoming powerful enough to
support the loss of efficiency inherent
in more complex languages
C++ was introduced in late 80’s

An object-oriented version of C
Last Update: 4/11
Page 8
Copyright (C) 2009 by David Figge. All Rights Reserved.
Why Object Oriented



OOP was born because the procedural
paradigm didn’t relate well to the real
world
In general, people don’t interact with
subroutines and variables
They interact with ‘objects’.

Entities that, within their own right, can
do things and have their own attributes
Last Update: 4/11
Page 9
Copyright (C) 2009 by David Figge. All Rights Reserved.
An Example Situation

Scenario

We want to model traffic on a freeway so
we can determine the best exit/entrance
locations


Wouldn’t it be nice if they really did this? 
Let’s look at this using traditional
methodology
Last Update: 4/11
Page 10
Copyright (C) 2009 by David Figge. All Rights Reserved.
Freeway Example (Traditional)
Variables Used
CarType(8)
CarSpeed(8)
CarAccel(8)
CarBrake(8)
CarLoc(8,2)
CarOn(8)
NumCars
Code
While (running)
for car 1 to 8
if running then
NewLoc(CarSpeed(car),CarAccel(car))
DrawCar(CarLoc(car))
end if
next car
Loop
End
Sub DrawCar
if CarType = 1 then
…
Page 11
4
2
3
6
5
7
Issues:
Code is complex, not intuitive, hard to maintain
Subs must deal with all cars (adds complexity)
What if more cars?
Last Update: 4/11
1
8
Copyright (C) 2009 by David Figge. All Rights Reserved.
Freeway Example (OOP)
Car Object
Type, accel
speed, etc. All kept in
object. Object knows
how to move and draw
itself based on settings
inside the object.
Code
While (running)
for each car
car.move()
car.draw()
next car
Loop
End
1
4
2
3
6
Advantages:
Each car object knows its own type and characteristics
Each car object knows how to move itself and draw itself
Code and data about the car are together, vastly
improving maintenance
As a separate entity, one person can work on car object
while another works on other parts
Last Update: 4/11
Page 12
5
7
8
Copyright (C) 2009 by David Figge. All Rights Reserved.
OOP In Practice

So a key point to take from this example:



Object Oriented Programming isn’t about rewriting
procedural code to use objects
It’s a fundamentally different approach to the problem
With procedural programming

You try to break down the project into tasks


In OOP

You determine how objects interact in the real world



Then each task into bite-sized chunks: functions
Then try to simulate that relationship in the program
By doing that, we more accurately represent the object
relationships that exist in the real world.
It’s a fundamentally different approach
Last Update: 4/11
Page 13
Copyright (C) 2009 by David Figge. All Rights Reserved.
Object Oriented Programming

Object Oriented Languages have four
characteristics




Inheritance
Encapsulation
Abstraction
Polymorphism
Last Update: 4/11
Page 14
Copyright (C) 2009 by David Figge. All Rights Reserved.
Inheritance

Inheritance is the ability to create one
object based on another

Let’s see how this works using animals as
an example…
Last Update: 4/11
Page 15
Copyright (C) 2009 by David Figge. All Rights Reserved.
Inheritance

Inheritance is the ability to create one
object based on another
Characteristics unique to
Mammals include live births
and having hair on their bodies
Mammal
Last Update: 4/11
Page 16
Copyright (C) 2009 by David Figge. All Rights Reserved.
Inheritance

Inheritance is the ability to create one
object based on another
Mammal
Canine
Last Update: 4/11
Because they are derived from
mammals, all canines also give live birth
and have hair on their bodies. These
traits are inherited from the base class
“mammal”. The canine class only
contains those elements that make
canines unique among mammals. For
example, they have two ears, four paws,
and a snout.
Page 17
Copyright (C) 2009 by David Figge. All Rights Reserved.
Inheritance

Inheritance is the ability to create one
object based on another
Mammal
Derived from Canine, Terriers
automatically have all characteristics of
canines (and therefore mammals).
Automatically. The Terrier class only
contains those attributes unique to this
breed (for example, their size
classifications).
Canine
Terrier
Last Update: 4/11
Page 18
Copyright (C) 2009 by David Figge. All Rights Reserved.
Inheritance

Inheritance is the ability to create one
object based on another
Mammal
Canine
Terrier
Last Update: 4/11
Again, Great Danes are
derived from Canine (and
therefore mammals). They,
however, have different
characteristics than Terriers
(such as their colors).
Great Dane
Page 19
Copyright (C) 2009 by David Figge. All Rights Reserved.
Inheritance

Inheritance is the ability to create one
object based on another
Mammal
Canine
Terrier
Last Update: 4/11
Great Dane
Inheritance – the ability to base one
class on another – simplifies objects and
better represents real-world situations.
Inheritance is an important aspect of
OOP.
Let’s discuss and diagram on the board
a class hierarchy for our freeway
problem…
Page 20
Copyright (C) 2009 by David Figge. All Rights Reserved.
Object Oriented Programming

Object Oriented Languages have four
characteristics




Inheritance
Encapsulation
Abstraction
Polymorphism
Last Update: 4/11
Page 21
Copyright (C) 2009 by David Figge. All Rights Reserved.
Encapsulation

Encapsulation is simply the ability to place the
code and variables that relate to one another
in the same place

In OOP, variables are Attributes, subs/functions
are Methods




These terms fit better into the concept of an object.
For example, a car keep Note
its size
a to
variable,
it’s just one
that Iin
tend
use the terms
attribute of that car.
variables and attributes
interchangeably,are
as wellput
as functions,
So the attributes and methods
together
methods, and subroutines (as they
into one unit: an object.
are, technically, the same). Don’t get
Since we’re here, let’s clarify
some
thrown
off by additional
that…
terms:


Last Update: 4/11
Class – The ‘blueprint’ for an object. Defines attributes
and methods within used by an object
Object – A specific instantiation of that class in memory
Page 22
Copyright (C) 2009 by David Figge. All Rights Reserved.
Object Oriented Programming

Object Oriented Languages have four
characteristics




Inheritance
Encapsulation
Abstraction
Polymorphism
Last Update: 4/11
Page 23
Copyright (C) 2009 by David Figge. All Rights Reserved.
Abstraction

Abstraction (or Data Hiding) is the ability
to protect attributes from outside access





May sound minor, but it’s not
It gives the object the ability to control how
and when attributes are accessed
A common practice is to make an attribute
(class variable) private, and have public
methods that set/get them.
This allows the object to validate the data,
and perhaps trigger other processes when
set/retrieved
Attributes and methods are hidden or shown
using the Public and Private keywords.
Last Update: 4/11
Page 24
Copyright (C) 2009 by David Figge. All Rights Reserved.
Object Oriented Programming

Object Oriented Languages have four
characteristics




Inheritance
Encapsulation
Abstraction
Polymorphism
Last Update: 4/11
Page 25
Copyright (C) 2009 by David Figge. All Rights Reserved.
Polymorphism

Polymorphism is the ability of a class to
override the behavior of a base class.
For example


In our car scenario, the base class
implementation of the ‘draw’ function
could just draw a simple box.
Each car derived from that can override
the ‘draw’ function (if desired) to draw a
likeness of the car.
Last Update: 4/11
Page 26
Copyright (C) 2009 by David Figge. All Rights Reserved.
Polymorphism

Another aspect of polymorphism is the
ability to view objects at multiple levels


In our freeway example, we can treat the
Honda Accord object as





This ties into inheritance as well
A Honda Accord
A Honda car
A generic car
A generic vehicle
So, just like in real life, objects can be
viewed at various levels

We’ll talk more about this as we cover
inheritance in more detail…
Last Update: 4/11
Page 27
Copyright (C) 2009 by David Figge. All Rights Reserved.
Object Oriented Programming

So, once again, Object Oriented
Languages have four characteristics





Inheritance
Encapsulation
Abstraction
Polymorphism
Questions on our intro to Object
Oriented concepts?
Last Update: 4/11
Page 28
Copyright (C) 2009 by David Figge. All Rights Reserved.
Object-Oriented Programming


In many OOP languages, including C#
and Java, classes are used to
implement the OO principles of
Inheritance, Encapsulation,
Abstraction, and Polymorphism
In OOP languages, a class defines a
type…
Last Update: 4/11
Page 29
Copyright (C) 2009 by David Figge. All Rights Reserved.
Objects and Classes

What’s a type?



What’s a class?




User-defined data type
A class combines data with the operations for
manipulating that data
Enables abstraction—the user of the class doesn’t
have to know what’s going on inside
What is an object?


Data and how it’s stored in memory (e.g. an
integer), and
Operations that can be performed using the data
object (e.g. +, -, etc.)
An instantiation (variable in memory) of a class
Class is the blueprint, object is the building
Last Update: 4/11
Page 30
Copyright (C) 2009 by David Figge. All Rights Reserved.
What’s this Public and Private?



The public and private keywords
control who has access to the data or
function
Private means only that class has
access to the data or function
Public means anyone can have access
to the data or function
Last Update: 4/11
Page 31
Copyright (C) 2009 by David Figge. All Rights Reserved.
Public or Private?

A general rule-of-thumb for public and
private variables is as follows:



Class variables are generally private. This
ensures that no outside parties change the
data without going through proper
procedures
Functions used only internally within the
class are private also.
Functions available to the ‘outside world’ are
public, and constitute the class’ interface.


These functions include functions to get and set
appropriate private class variables as well
Let’s look at an example of a class…
Last Update: 4/11
Page 32
Copyright (C) 2009 by David Figge. All Rights Reserved.
Employee Class Example

This is a class
described using a
language called UML




Unified Modeling
Language
Classes describe both
data and behavior, so
after the name of the
class we have two
sections


Employee
-socialSecurityNumber:String
-gender:boolean
-dateOfBirth:Date
+getSocialSecurityNumber:String
+getGender:boolean
+getDateOfBirth:Date
+setSocialSecurityNumber:void
+setGender:void
+setDateOfBirth:void
The first section describes the data
The second describes the behavior, or methods
The – means private (only the class can access it)
The + means public (everyone can access it)
Last Update: 4/11
Page 33
Copyright (C) 2009 by David Figge. All Rights Reserved.
Employee Class Example

What you see is pretty
typical for a class.





Employee
-socialSecurityNumber:String
-gender:boolean
-dateOfBirth:Date
+getSocialSecurityNumber:String
+getGender:boolean
+getDateOfBirth:Date
+setSocialSecurityNumber:void
+setGender:void
+setDateOfBirth:void
Data elements are
marked as private
Methods that are
part of the class’
public interface are
marked public
If there were any
“helper” methods, used
only internally, they
would be private as well
After the data elements, you see a : and the data type
used to contain that data (gender:boolean)
After the methods, you see the data type returned from
the method (getGender:boolean). Void means none
Last Update: 4/11
Page 34
Copyright (C) 2009 by David Figge. All Rights Reserved.
Employee Class Example


Employee
As a final note for
this example, you
-socialSecurityNumber:String
-gender:boolean
can see that for
-dateOfBirth:Date
each data item we
+getSocialSecurityNumber:String
have two functions
+getGender:boolean
that reference them,
+getDateOfBirth:Date
a ‘get’ function and
+setSocialSecurityNumber:void
a ‘set’ function.
+setGender:void
We call these
+setDateOfBirth:void
“getters and
setters”. They allow access to the data, but only in
a controlled way


The Set function can validate the new SSN
to validate the format, for example
We’ll talk more about how C# uses properties as
getters and setters…
Last Update: 4/11
Page 35
Copyright (C) 2009 by David Figge. All Rights Reserved.
Employee Class Example


Since we’re here,
a note about object
stability
It is the class’
responsibility to
make sure that it
is always in a valid
state for use, even
if it is empty


Employee
-socialSecurityNumber:String
-gender:boolean
-dateOfBirth:Date
+getSocialSecurityNumber:String
+getGender:boolean
+getDateOfBirth:Date
+setSocialSecurityNumber:void
+setGender:void
+setDateOfBirth:void
If all classes adhere to this, then the system is
always stable
The Getters and Setters help keep this
class object stable.
Last Update: 4/11
Page 36
Copyright (C) 2009 by David Figge. All Rights Reserved.
Pop Quiz!
Name: ___________________
Question 1 of 4
What is a class?
A grouping of data and methods.
Last Update: 4/11
Page 37
Copyright (C) 2009 by David Figge. All Rights Reserved.
Pop Quiz!
Name: ___________________
Question 2 of 4
What is the relationship between class
functions (methods) and class data
members?
The methods use the data in order to
perform a specific task.
Last Update: 4/11
Page 38
Copyright (C) 2009 by David Figge. All Rights Reserved.
Pop Quiz!
Name: ___________________
Question 3 of 4
What is the relationship between an object
and a class?
An object is an instantiation of a class. A
class is a ‘blueprint’ or pattern used to
create the object.
Last Update: 4/11
Page 39
Copyright (C) 2009 by David Figge. All Rights Reserved.
Pop Quiz!
Name: ___________________
Question 4 of 4
Explain how a class can accomplish
abstraction.
Using the public and private keywords to
restrict outside access to internal data
and methods.
Last Update: 4/11
Page 40
Copyright (C) 2009 by David Figge. All Rights Reserved.
Let’s build a Calculator


I’d like to take these concepts we’ve discussed
and try them out
Team up with a partner near you and (on paper)
identify the objects and relationships involved
for a 4-function calculator (add, subtract,
multiply, and divide)




So, what objects are in a calculator? How do they
interact with one another?
Remember, you don’t need to consider “how will
this get coded?”
This would be a computer version of a calculator,
made to simulate a desktop calculator.
After you’re done, we’ll translate that class
design into code together
10 Minutes
Last Update: 4/11
Page 41
Copyright (C) 2009 by David Figge. All Rights Reserved.
Calculator Example

Okay, so what did you come up with?

Here’s what I came up with…
Last Update: 4/11
Page 42
Copyright (C) 2009 by David Figge. All Rights Reserved.
Calculator Example
Equally important would be the
The operation keys take
the
number
number
keys. You need to be able to
Objects:
you’ve entered, save it, andDisplay
allowenter
you numbers!
to enter the other number in the
As I looked at the current objects, I
operation.
felt the relationship between the
•Display
operators and = key
Finally, the =+key takes
the number
1 were2 significant.
3
•Number
keys
It makes an simpler
design
(and
one
saved (by
keys) and the
It seems like a pretty key element
ofthe
a operator
•Operator
keys
more representative
of theisrealcurrent
number
entered,
performs
the
calculator
the
display.
This
object
is
4
5
6
world) to have a Calculator
object
Note (or
that it’s
common
to create
•Equals
key
calculation,
andpretty
produces
a result.
responsible
for taking a number
(kinda like the CPU). It’s responsible
an object representing
a concept
string)
and
displaying
it.
•Calculator
7 and8performing
9
for storing numbers
(“time”) X
or more abstract element.
calculations.
Even if it’s just too make an easier
.
0
=
/ it’s totally okay.
design,
Calculator
Ready to build this?
Last Update: 4/11
Page 43
Copyright (C) 2009 by David Figge. All Rights Reserved.
Calculator Example

We’re going to build this using
Windows Forms


Note that – because of how Windows
Forms work – we can’t easily put the
buttons in a class together.


We’ll hit Windows Forms more in depth a
little later in the course…
We’ll get around this a bit by making
them all execute the same code
underneath…
Here we go…
Last Update: 4/11
Page 44
Copyright (C) 2009 by David Figge. All Rights Reserved.
Calculator
Calculator Demo…
Last Update: 4/11
Page 45
Copyright (C) 2009 by David Figge. All Rights Reserved.
Initializing Member Variables

Problem:


Using a class object with member variables that
have not been initialized can cause problems
However, declaring a class variable does not
necessarily initialize the member variables


Using the { . . . } structure initialization syntax
works for classes, but only if all member variables
are public


You can initialize variables with =, but that doesn’t work
for complex objects or ones that require runtime
information to initialize
And, as we discussed, that’s hardly ideal…
One solution: You could have a member
function that does the initialization

But what if the user of the class forgot to call it?
Last Update: 4/11
Page 46
Copyright (C) 2009 by David Figge. All Rights Reserved.
Constructors

The OOP (and C#) answer to this problem is
constructors


Constructors are special member functions
whose purpose is to initialize the object into a
known stable state.
Constructors have the same name as the name of
the class


A constructor is always called when the class
object is created


They don’t have any return type either, as it’s a given
that they return an instantiated object of the class
If you don’t supply a constructor, the compiler supplies a
simple constructor for you
Constructors are typically not private

Somewhat awkward to call it that way…
Last Update: 4/11
Page 47
Copyright (C) 2009 by David Figge. All Rights Reserved.
Constructors

You can have as many constructors as you wish

Normal overloading rules apply


The constructor with no parameters is called the Default
Constructor


The parameters must change
Because it is used to initialize the object into its default
state (as no values were supplied)
Remember I mentioned if you don’t create a constructor,
one is created for you by the compiler


It’s sole purpose is so that you can create an object of that
class
It creates a version of the default constructor


It does nothing outside of declared initializations, as it doesn’t
know what additional steps to take
If you define any constructors (default or not), the compiler
will not define the default constructor for you.
Last Update: 4/11
Page 48
Copyright (C) 2009 by David Figge. All Rights Reserved.
Constructor Exercise

Going back to our Check Register program

From an OOP design standpoint, it would make
more sense to have the transaction records be
objects, wouldn’t it



Let’s work together to create a Transaction
class, along with a constructor to initialize it


That way each transaction knows about it’s
transaction type, payee, amount, etc.
It also better represents the real world, where each
transaction is an individual entity unto itself.
Then we’ll modify the Main code to use an array
of transaction objects rather than using the
Trans class…
Ready?
Last Update: 4/11
Page 49
Copyright (C) 2009 by David Figge. All Rights Reserved.
Transaction Code
class Transaction
{
TransType type;
int checkNum;
string payee;
decimal amount;
DateTime date;
// New Transaction class
public Transaction(TransType trantype, int cknum,
string paidto, decimal amt, DateTime dt)
{
type = trantype;
checkNum = cknum;
payee = paidto;
amount = amt;
date = dt;
}
}
Transaction[] trnsactns;
// In main code module
trnsactns = new Transaction[transactions.NumTrans];
for (int x = 0; x < transactions.NumTrans; x++)
trnsactns[x] = new Transaction(transactions.GetType(x),
transactions.GetCheckNum(x), transactions.GetPayee(x),
transactions.GetAmount(x),transactions.GetDate(x));
Last Update: 4/11
Page 50
Copyright (C) 2009 by David Figge. All Rights Reserved.
Your Turn!

Create a public interface to the Transaction class

Provide Getters and Setters, with the setters
validating the input as needed





Check numbers: 0 (if not check transaction), not negative if
check transaction
Payee should not be blank unless deposit
Amount must be positive value
Date must be > 2 months ago
Modify your existing code to use the transaction
records you just created and the interface you just
implemented.

The transactions variable is still used for information about
the collection as a whole (like the total number of
transactions)
45 Minutes
Last Update: 4/11
Page 51
Copyright (C) 2009 by David Figge. All Rights Reserved.
End of Session 2
Windows and Web Apps in C#
Last Update: 4/11
Page 52
Copyright (C) 2009 by David Figge. All Rights Reserved.
Descargar

Advanced Language Concepts in C#