Date post: | 19-Dec-2015 |
Category: |
Documents |
View: | 218 times |
Download: | 1 times |
Copyright (C) 2009 by David Figge. All Rights Reserved.
Windows and Web Apps in C#
David [email protected]
Session 2
Last Update: 4/11 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.
Windows and Web Apps in C#
Object Oriented Concepts
Last Update: 4/11 Page 3
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 Copyright (C) 2009 by David Figge. All Rights Reserved.Page 4
A Little History
Computers came into being about 50 years ago The first ones were very simple
Computers were good at taking a simple task and doing it many times A first use was missile trajectories
Not surprisingly, code was procedural Simple steps with loop instructions
Last Update: 4/11 Copyright (C) 2009 by David Figge. All Rights Reserved.Page 5
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 Assembly, BASIC, C, Forth, Pascal, RPG…
Last Update: 4/11 Copyright (C) 2009 by David Figge. All Rights Reserved.Page 6
Code
Example Procedural Example
10. REM Calculate power20. INPUT “Enter base number: “, B30. INPUT “Enter power: “, P40. SET N=B50. P = P – 160. IF P = 0 THEN 9070. N = N * B80. GOTO 5090. PRINT N100. END
Last Update: 4/11 Copyright (C) 2009 by David Figge. All Rights Reserved.Page 7
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 Copyright (C) 2009 by David Figge. All Rights Reserved.Page 8
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 Copyright (C) 2009 by David Figge. All Rights Reserved.Page 9
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 Copyright (C) 2009 by David Figge. All Rights Reserved.Page 10
Freeway Example (Traditional)
11
33
22
55
44
66
77
88
Variables UsedCarType(8)
CarSpeed(8)CarAccel(8)CarBrake(8)CarLoc(8,2)CarOn(8)NumCars
Issues:Code is complex, not intuitive, hard to maintainSubs must deal with all cars (adds complexity)What if more cars?
CodeWhile (running) for car 1 to 8 if running then NewLoc(CarSpeed(car),CarAccel(car)) DrawCar(CarLoc(car)) end if next carLoopEnd
Sub DrawCar if CarType = 1 then …
Last Update: 4/11 Copyright (C) 2009 by David Figge. All Rights Reserved.Page 11
Freeway Example (OOP)
11
33
22
55
44
66
77
88
Car ObjectType, accelspeed, etc. All kept in object. Object knows how to move and draw itself based on settings inside the object.
Advantages:Each car object knows its own type and characteristicsEach car object knows how to move itself and draw itselfCode and data about the car are together, vastly improving maintenanceAs a separate entity, one person can work on car object while another works on other parts
CodeWhile (running) for each car car.move() car.draw() next carLoopEnd
Last Update: 4/11 Copyright (C) 2009 by David Figge. All Rights Reserved.Page 12
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
Then each task into bite-sized chunks: functions In OOP
You determine how objects interact in the real world 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
Object Oriented Programming
Object Oriented Languages have four characteristics Inheritance Encapsulation Abstraction Polymorphism
Last Update: 4/11 Copyright (C) 2009 by David Figge. All Rights Reserved.Page 14
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 Copyright (C) 2009 by David Figge. All Rights Reserved.Page 15
Inheritance
Inheritance is the ability to create one object based on another
MammalCharacteristics unique to
Mammals include live birthsand having hair on their bodies
Last Update: 4/11 Copyright (C) 2009 by David Figge. All Rights Reserved.Page 16
Inheritance
Inheritance is the ability to create one object based on another
Mammal
Canine
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.
Last Update: 4/11 Copyright (C) 2009 by David Figge. All Rights Reserved.Page 17
Inheritance
Inheritance is the ability to create one object based on another
Mammal
Canine
Terrier
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).
Last Update: 4/11 Copyright (C) 2009 by David Figge. All Rights Reserved.Page 18
Inheritance
Inheritance is the ability to create one object based on another
Mammal
Canine
Terrier Great Dane
Again, Great Danes are derived from Canine (and
therefore mammals). They, however, have different
characteristics than Terriers (such as their colors).
Last Update: 4/11 Copyright (C) 2009 by David Figge. All Rights Reserved.Page 19
Inheritance
Inheritance is the ability to create one object based on another
Mammal
Canine
Terrier 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…
Last Update: 4/11 Copyright (C) 2009 by David Figge. All Rights Reserved.Page 20
Object Oriented Programming
Object Oriented Languages have four characteristics Inheritance Encapsulation Abstraction Polymorphism
Last Update: 4/11 Copyright (C) 2009 by David Figge. All Rights Reserved.Page 21
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 its size in a variable, it’s just
one attribute of that car. So the attributes and methods are put together
into one unit: an object. Since we’re here, let’s clarify some additional
terms: Class – The ‘blueprint’ for an object. Defines attributes
and methods within used by an object Object – A specific instantiation of that class in memory
Note that I tend to use the terms variables and attributes
interchangeably, as well as functions, methods, and subroutines (as they
are, technically, the same). Don’t get thrown off by that…
Last Update: 4/11 Copyright (C) 2009 by David Figge. All Rights Reserved.Page 22
Object Oriented Programming
Object Oriented Languages have four characteristics Inheritance Encapsulation Abstraction Polymorphism
Last Update: 4/11 Copyright (C) 2009 by David Figge. All Rights Reserved.Page 23
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 Copyright (C) 2009 by David Figge. All Rights Reserved.Page 24
Object Oriented Programming
Object Oriented Languages have four characteristics Inheritance Encapsulation Abstraction Polymorphism
Last Update: 4/11 Copyright (C) 2009 by David Figge. All Rights Reserved.Page 25
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 Copyright (C) 2009 by David Figge. All Rights Reserved.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 This ties into inheritance as well
In our freeway example, we can treat the Honda Accord object as 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
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 Copyright (C) 2009 by David Figge. All Rights Reserved.Page 28
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 Copyright (C) 2009 by David Figge. All Rights Reserved.Page 29
Objects and Classes
What’s a type? 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.) 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?
An instantiation (variable in memory) of a class Class is the blueprint, object is the building
Last Update: 4/11 Copyright (C) 2009 by David Figge. All Rights Reserved.Page 30
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 Copyright (C) 2009 by David Figge. All Rights Reserved.Page 31
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 Copyright (C) 2009 by David Figge. All Rights Reserved.Page 32
Employee Class Example
This is a classdescribed using alanguage called UML
Unified ModelingLanguage
Classes describe bothdata and behavior, soafter the name of theclass we have twosections
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)
Employee-socialSecurityNumber:String-gender:boolean-dateOfBirth:Date+getSocialSecurityNumber:String+getGender:boolean+getDateOfBirth:Date+setSocialSecurityNumber:void+setGender:void+setDateOfBirth:void
Last Update: 4/11 Copyright (C) 2009 by David Figge. All Rights Reserved.Page 33
Employee Class Example
What you see is prettytypical for a class.
Data elements aremarked as private
Methods that arepart of the class’public interface aremarked public
If there were any“helper” methods, usedonly 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
Employee-socialSecurityNumber:String-gender:boolean-dateOfBirth:Date+getSocialSecurityNumber:String+getGender:boolean+getDateOfBirth:Date+setSocialSecurityNumber:void+setGender:void+setDateOfBirth:void
Last Update: 4/11 Copyright (C) 2009 by David Figge. All Rights Reserved.Page 34
Employee Class Example
As a final note forthis example, youcan see that foreach data item wehave two functionsthat reference them,a ‘get’ function anda ‘set’ function.
We call these“getters andsetters”. They allow access to the data, but only in a controlled way
The Set function can validate the new SSNto validate the format, for example
We’ll talk more about how C# uses properties as getters and setters…
Employee-socialSecurityNumber:String-gender:boolean-dateOfBirth:Date+getSocialSecurityNumber:String+getGender:boolean+getDateOfBirth:Date+setSocialSecurityNumber:void+setGender:void+setDateOfBirth:void
Last Update: 4/11 Copyright (C) 2009 by David Figge. All Rights Reserved.Page 35
Employee Class Example
Since we’re here,a note about objectstability
It is the class’responsibility tomake sure that itis always in a validstate for use, evenif it is empty If all classes adhere to this, then the system is
always stable The Getters and Setters help keep this class
object stable.
Employee-socialSecurityNumber:String-gender:boolean-dateOfBirth:Date+getSocialSecurityNumber:String+getGender:boolean+getDateOfBirth:Date+setSocialSecurityNumber:void+setGender:void+setDateOfBirth:void
Last Update: 4/11 Copyright (C) 2009 by David Figge. All Rights Reserved.Page 36
Name: ___________________Pop Quiz!Question 1 of 4
What is a class?
A grouping of data and methods.
Last Update: 4/11 Copyright (C) 2009 by David Figge. All Rights Reserved.Page 37
Name: ___________________Pop Quiz!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 Copyright (C) 2009 by David Figge. All Rights Reserved.Page 38
Name: ___________________Pop Quiz!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 Copyright (C) 2009 by David Figge. All Rights Reserved.Page 39
Name: ___________________Pop Quiz!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 Copyright (C) 2009 by David Figge. All Rights Reserved.Page 40
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 MinutesLast Update: 4/11 Copyright (C) 2009 by David Figge. All Rights Reserved.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
Last Update: 4/11 Page 43
Display
1 2 3
4 5 6
7 8 9
. 0 =
+
-
X
/
It seems like a pretty key element of a calculator is the display. This object is responsible for taking a number (or
string) and displaying it.
Equally important would be the number keys. You need to be able to enter
numbers!
The operation keys take the number you’ve entered, save it, and allow you
to enter the other number in the operation.
Finally, the = key takes the number saved (by the operator keys) and the
current number entered, performs the calculation, and produces a result.
Calculator
As I looked at the current objects, I felt the relationship between the
operators and = key were significant. It makes an simpler design (and one
more representative of the real-world) to have a Calculator object (kinda like the CPU). It’s responsible for storing
numbers and performing calculations.
Note that it’s pretty common to create an object representing a concept
(“time”) or more abstract element. Even if it’s just too make an easier
design, it’s totally okay.
Objects:
•Display•Number keys•Operator keys•Equals key•Calculator
Ready to build this?
Copyright (C) 2009 by David Figge. All Rights Reserved.
Calculator Example
We’re going to build this using Windows Forms We’ll hit Windows Forms more in depth
a little later in the course… Note that – because of how Windows
Forms work – we can’t easily put the buttons in a class together. 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
Last Update: 4/11 Page 45
Calculator Demo…
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
You can initialize variables with =, but that doesn’t work for complex objects or ones that require runtime information to initialize
Using the { . . . } structure initialization syntax works for classes, but only if all member variables are public
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 Copyright (C) 2009 by David Figge. All Rights Reserved.Page 46
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
They don’t have any return type either, as it’s a given that they return an instantiated object of the class
A constructor is always called when the class object is created
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 Copyright (C) 2009 by David Figge. All Rights Reserved.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 parameters must change The constructor with no parameters is called the
Default Constructor 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
Last Update: 4/11
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
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.
Let’s work together to create a Transaction class, along with a constructor to initialize it Then we’ll modify the Main code to use an array of
transaction objects rather than using the Trans class…
Ready?
Page 49
Copyright (C) 2009 by David Figge. All Rights Reserved.
Code
Example Transaction Code
class Transaction // New Transaction class{ TransType type; int checkNum; string payee; decimal amount; DateTime date;
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!
Last Update: 4/11
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)
Page 51
45 Minutes