Creating Object Oriented Programs

Download Report

Transcript Creating Object Oriented Programs

OOP: Creating
Object-Oriented
Programs
VB & Object Oriented
Programming


Objects have properties, methods, and generate
events
Classes have been predefined up until now





Text box class
Form or command button class
Languages such as Java and Smalltalk were
designed to be OO from the beginning
VB has evolved and modified to accommodate OOP
VB.NET supports writing object oriented (OO)
programs
Object Terminology Review

Object - like a noun, a thing


Properties - like an adjective, characteristics of
object


Text, ForeColor, Checked, Visible, Enabled
Methods - like a verb, an action or behavior,
something the object can do or have done to it


Buttons, Text Boxes, Labels
ShowDialog, Focus, Clear, ToUpper, ToLower
Events - object response to user action or other
events

Click, Enter, Activate
3
Thus Far . . .




Since day 1 we have been using objects
Up until now the classes for all objects used
have been predefined
We have created new objects for these
classes by using the controls in the Toolbox
VB allows programmers to create their own
object types by creating a Class Module
4
Class and Instance




When we add a button object from the
button tool in the toolbox to the form we
are creating an Instance of the Button
Class
The button object is an Instance of the
Button Class
Every button on the form is an Instance
Defining your own Class is like creating a
new tool for the Toolbox
5
Class Modules



VB allows you to create your own new
objects with a class module.
User-created class modules have properties
and methods.
A tool such as the command button in a tool
box is the object class.
Classes and Objects



A command button on a form is an instance
of the class—an object.
Creating your own class is similar to adding a
tool to the toolbox.
A cookie cutter is a metaphor for a class. You
create many cookies (objects) with the cutter
(a class). Each cookie is a new instance of an
object of the cookie cutter class.
Defining a New Class



Defining your new class is like creating a new
tool for the toolbox – the process does not
create the object, only a definition of what the
object looks like and how it will behave.
You may then create as many instances of
the class as you like
e.g. your class may be employee, student,
product etc
OOP Characteristics
 Object Oriented Programming (OOP) says
that a true object oriented language has the
following three characteristics;
1) encapsulation
2) polymorphism
3) inheritance
Encapsulation




Combination of characteristics of an object
along with its behavior in "one package"
Cannot make object do anything it doesn't
already "know" how to do
Cannot make up new properties, methods,
or events
Sometimes referred to as data hiding;an
object can expose only those data
elements and procedures that it wishes
10
Polymorphism

Different classes of objects may have
behaviors that are named the same but are
implemented differently

Printer.print behaves differently from
PictureBox.print, even though “print” is the
method used for each.
11
Inheritance


Ability to create a new class from an existing
class
Purpose of Inheritance is reusability

The new ones take on all the behaviors and
properties of the parents from which they are cloned.

In each form created is inherited from the
existing Form class


Original class is called Base Class, Superclass, or
Parent Class
Inherited class is called Subclass, Derived Class, or
Child Class
12
Example of Inheritance in VB.NET

Examine 1st line of code for a form in the
Editor (look at Visual Studio 2005 in the labs)
Inherited Class, Derived Class Subclass, Child Class
Public Class Form1
Inherits System.Windows.Forms.Form
Base Class, Superclass, Parent Class
13
Hello World in VB.NET
Goal of Inheritance

Base Class
Person
Person
Subclasses
-Name
-Address
-Phone





Employee
Customer
Student
Employee
Customer
Student
15
VB & Object Oriented
Programming




Big advantage of OOP is the ability to reuse
objects.
Reusing objects saves time and effort
New classes created with a Class Module
can be used in multiple projects
You can create three objects from the same
class, yet you can set their properties
differently.
Reusability



Reusability means that you do not have to
reinvent the wheel each time you create an
application e.g. you can create a class for
data access that can be reused.
Reusing code that has previously been tested
and debugged saves you time
Organisations can create applications more
rapidly
Multitier Applications



Common use of classes is to create
multitier applications
Each of the functions of a multitier
application can be coded in a separate
component and stored and run on different
machines
Goal is to create components that can be
combined and replaced
18
Three-tier Model

Most common implementation of multitier
Presentation Tier
Business Tier
User Interface
Forms
Controls
Menus
Business Objects
Validation
Calculations
Business Logic
Business Rates
Data Tier
Data Retrieval
Data Storage
19
Classes and Objects
this represents the class
Textbox
these represent objects—
instances of the class
Classes



Design new behaviors and properties for
classes you create
You assign property values in your class
You assign properties or reveal them with
Property Get and Property Let procedures
Accessing the Values of a
Class

The Property Get procedure retrieves a property
from a class, making it available to the outside
world.

The Property Let procedure assigns a value from
the outside world to a property of the class.

Property Let and Property Get are the only way to
assign and retrieve property values for a class.

Otherwise, there is no other “doorway” through
which they can pass.
Property Procedures
Form of the two procedures:
[Public] Property Get Procedurename ([optional arg list]) [As datatype]
statements in the procedure
Procedurename = Propertyname
End Property
[Public] Property Let Procedurename ([optional arg list])IncomingValue
_ [As datatype]
statements in the procedure
Propertyname = Procedurename
End Property
Example
Public Property Get LastName() As String
LastName = mstrLastName
End Property
Creating a New Class
1)
2)
3)
4)
5)
Define a new class module
Define the class properties
Add property procedures
Create a method
Save the class module

Define a new class module:

Open a new project

Select Add Class Module from the Project menu

Click the New tab and choose Class Module; click Open

Change the class name to one of your choosing (CProduct in this case)
New tab
class module selection
new name
Defining Class Properties




Declare properties of a class with variables
(called instance variables)
Variables are private and placed in General
Declarations section
Add property Let and Get procedures for each
instance variable
Code a method, which is a class’ behavior
Defining Class Properties

Define three class properties (instance variables):







Private mcurPrice
As Currency
Private mintQuantity As Integer
Private mstrDescription As String
Only procedures within the class can access the
properties defined as private
To provide a “window” through which properties can be
retrieved or set, you code special methods called
property procedures.
Add Property Procedures, select Add Procedure from
the Tools menu, name the property by naming the
Procedure in the Name text box, and select options
Property and Public.
The Quantity property of the new class is defined this
way—with two property procedures (also called accessor
methods)
instance variables
property
procedures for the
mintQuantity
instance variable
Creating a New Object Using a Class




Creating a class module defines a new class
Code that creates and uses objects is placed
in form and code modules, whereas a class
must be placed in a class module
Create an object of a class with the New
keyword—called instantiating an object
The New keyword creates a new instance of a
class when the object is first used

Dimensioning objects with the New keyword:



Dim Employee As New cEmployee
Private mInventory
As New Cinventory
Next, create a form that instantiates an object
of the class CProduct
Collections



You can create your own or use collections
built in to VB
Each project has a Controls collection and a
Forms collection
You can use a For Each… Next statement to
set properties of multiple controls
For Each/Next Statements
There is a need to have a method of reference to each Element in
an Array
A For/Next Loop can be used, however, another useful looping
construct is the For Each/Next Loop; the significant advantage of
using the For Each/Next Loop,is that the Subscripts of the Array do
not have to be manipulated
For Each ElementName In ArrayName
Statement(s) in Loop
Next ElementName
For Each ElementName In ArrayName
Statement(s) in Loop
Next ElementName
VB automatically references each Element of the
Array, assigns its value to ElementName, and
makes one pass through the loop
If the Array has n Elements, the loop will execute
n times
The Variable used for ElementName must be a
Variant Data Type
Examle: Using an array named stName, print each element of the
array
Dim vOneName As Variant
For Each vOneName In stName
Print vOneName‘Print one element of the array
Next vOneName
The For Each/Next loop will execute if the array has at least one
element; All the statements within the body of the loop
are executed for the each element in the array
Furthermore, an Exit For Statement may be used within the loop to
exit early, just as in a For/Next loop
Using a For Each… Next Loop
Private Sub cmdExit_Click()
‘this procedure will unload all forms that are currently loaded
‘in the project
Dim OneForm As Form
For Each OneForm in Forms
Unload OneForm
Next
End
This is a very useful piece of code for quitting a project
Disabling Controls using a For
Each…Next Loop
Dim AnyControl As Control
For Each AnyControl in frmMain.Controls
AnyControl.Enabled = False
Next
Uses the controls collection to change a property of multiple
controls
Collections


A Collection Class holds references for a
series of objects created from the same class
or from different classes
Actually a collection holds references to the
objects


You reference by Index Number or a Key
Similar to list box and the associated items in the
list box
Key for Collection Objects




Key must be a string
Can be used to reference individual objects in
the collection
Declare the Key as String at the module level
of the Class module for the object (not the
collection)
Add Property Get and Let procedures
Collections
Create a collection by writing a new class module and
then declaring an object variable (to create an
object).
Each object in the collection is known as an item.
Each object has a position known as its index.
A collection is declared with a Dim, Public, or Static
statement just like any other object variable:
Dim mProducts As New Collection
VB always updates the Count property of a collection
every time you add or remove an item from a
collection.
Collections
The Add method adds an item to the collection.
mProducts.Add Prod1
The Remove method removes an item according to its
index in the collection.
mProducts.Remove 2
It is best to provide a unique key to each object in a
collection, rather than rely upon an index (see
remove example above). It is difficult to associate an
index with a particular product. Using a key value
makes locating an object much easier.
Add a string in the CProduct class: Private
mstrProductCode As String
Use the string to add an object to a collection or
remove it from a collection
Using a Collection in a Form
Using the Object Browser




Object Browser reveals names of objects,
properties, methods, events, and VB
constants
View objects: View, Object Browser
Object Browser is best way to look up an
object’s available properties, methods, etc.
Select an object and press F1 for help
Method symbol
ComboBox is
selected object
Property symbol
Event symbol
Description