110-I 1
Object Terminology Review• Object - like a noun, a thing
– Buttons, Text Boxes, Labels• 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– ShowDialog, Focus, Clear, ToUpper, ToLower
• Events - object response to user action or other events– Click, Enter, Activate
110-I 2
So Far . . .
• Since Chapter 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
110-I 3
• The class is the blueprint for the object. It describes– The data contained in the object
(properties)– The actions that the object can perform
(methods, event procedures)
An object is an instance of a class.
What is a Class?
110-I 4
• Defining a class does not create an object, only a definition of what that type of object looks like and behaves.
• Example: the Button class. You can have many buttons in your project (many instances of the Button class). Each button will have its own properties; different text, different name, different code for the event procedures.
A Class vs. an Object (1)
110-I 5
A Class vs. an Object (2)
• 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
• Every button on the form is an Instance of the Button Class
• Defining your own Class is like creating a new tool for the Toolbox
110-I 6
"Cookie Analogy"
• Class = Cookie cutter• Instantiate = Making a cookie using the
cookie cutter• Instance = Newly made cookie• Properties of the Instance may have
different values– Icing property can be True or False– Flavor property could be Lemon or Chocolate
110-I 7
"Cookie Analogy" (cont.)
• Methods = Bake
• Events = Cookie crumbling when you step on it accidentally
110-I 8
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
• The details of the implementation of the class are not relevant (they are hidden) to the user of the class.
110-I 9
Reusability
• The main purpose behind OOP and Inheritance in particular
• New classes created with Class Module can be used in multiple projects
• Each object created from the class can have its own properties
110-I 10
Class Design - Analyze:
• Characteristics of your new objects– Characteristics will be properties– Define the properties as module level variables
in the class module
• Behaviors of your new objects– Behaviors will be methods– Define the methods as sub procedures and
functions in the class module
110-I 11
Create a New Class
Add Class Module to your project
• 1. Go to New Item dialog, choose Class
• 2. Name the Class
• 3. Define the Class properties
• 4 .Code the methods
STEPS:
110-I 12
Properties of a Class
• Define variables inside the Class Module by declaring them as Private at module level.
• Do not make them Public-that would violate Encapsulation (each object should be in charge of its own data)
• Private mintPatientNum as Integer
• Private mdtmDate as DateTime
• Private mstrLastName as String
110-I 13
Assign Values to Properties• Write special property procedures to
– Pass the values to the class module– Return values from the class module
• Name used for property procedure is the name of the property seen by the outside world
• Property Get– Retrieves property values from a class– Like a function must return a value
• Property Set– Sets or assigns values to properties
110-I 14
Property Procedure General Form
Private ClassVariable As DataType[Public] Property PropertyName As DataType
GetReturn ClassVariable
End Get
Set (ByVal Value As DataType)[statements, such as validation]ClassVariable = Value
End SetEnd Property
110-I 15
Read-Only Properties
• In some instances a value for a property should only be retrieved by an object and not changed– Create a read-only property by using the
ReadOnly modifier– Write only a Get portion of the property
procedure
[Public] ReadOnly Property PropertyName As DataType
110-I 16
Code a Method
• Create methods by adding sub procedures and functions for the behaviors to the class module (just like we have up to now).
• The sub procedures and functions should be defined as Public unless there are going to be used for implementation purposes.
110-I 17
Analyze the characteristics (properties) and behaviors (methods) of your object
Write Property Procedures to assign and retrieve the properties of the classIt allows us to declare all module variables (properties) private
Write Sub Procedures and Functions for the behaviors of the class
Summary:Defining a Class(1)
110-I 18
Writing Property Procedures
(they are public by default)
Private mstrLastName As String
Property LastName( ) As String
Get
Return mstrLastName
End Get
Set (ByVal Value As String)
mstrLastName= Value
End Set
End Property
Declaration of property
Property P
rocedure
Returns value of property
Sets value of property (needs argument)
Summary:Defining a Class(2)
110-I 19
Read Only Property Procedures
Example:
Private mstrLastName As String
ReadOnly Property LastName( ) As String
Get
Return mstrLastName
End Get
End Property
Declaration of property
Property P
rocedure
Returns value of property
Summary:Defining a Class(3)
110-I 20
BookSale class• Three private instance variables
- mstrTitle
- mintQuantity
- mdecPrice• Three public property Procedures
– Title– Quantity– Price
• One public method– ExtendedPrice
The class diagram is incomplete (e.g., no type for the instance variables, no information about the method)
110-I 21
Public Class BookSale ‘ Class Name: BookSale
Private mstrTitle As String
Private mintQuantity As Integer
Private mdecPrice As Decimal
‘Property Procedures
Property Title( ) As String
Get
Return mstrTitle
End Get
Set (ByVal Value As String)
mstrTitle= Value
End Set
End Property
A complete class code (1)
110-I 22
Property Quantity( ) As Integer
Get
Return mintQuantity
End Get
Set (ByVal Value As Integer)
mintQuantity= Value
End Set
End Property
Property Price( ) As Decimal
Get
Return mdecPrice
End Get
Set (ByVal Value As Decimal)
mdecPrice= Value
End Set
End Property
A complete class code (2)
110-I 23
‘write the methods
Public Function ExtendedPrice() As Decimal
Return CDec(mintQuantity* mdecPrice)
End Function
End Class
A complete class code (3)
110-I 24
Creating a New Object Using a Class
Steps
• Declare a variable for the new object with datatype of the class
• Then, instantiate the object using the New keyword
110-I 25
Instantiating An Object
• Creating a new object based on a class
• Create an instance of the class by using the New keyword and specify the class
New className ( )
110-I 26
Examples of InstantiatingAn Object
Dim fntMyFont = New Font ("Arial", 12)lblMsg.Font = fntMyFont
OR
lblMsg.Font = New Font ("Arial", 12)
110-I 27
Best Practices
• You may declare and instantiate an object at the same time but it is not the best practice
• Should declare the variable separately in the Declarations section
• Instantiate the object– Only when(if) it is needed– Inside a Try/Catch block for error handling
(Try/Catch block must be inside a procedure)
110-I 28
Example using our class Public Class frmBookSale : Inherits System.Windows.Forms.Form
Private mBookSale As BookSale ‘declare module level variable
Private Sub mnuFileCalculateSale(..)
Try
mBookSale = New BookSale() 'instantiate the object
'Set the properties of the booksale object
mBookSale.Title = txtTitle.Text
mBookSale.Quantity = CInt(txtQuantity.Text)
mBookSale.Price = CDec(txtPrice.Text)
‘Display the book title and calculate and format the result
lblTitle.Text=mBookSale.Title
lblExtendedPrice.Text = FormatCurrency(mBookSale.ExtendedPrice())
Catch 'display message if there is an error
MessageBox.Show("Please make sure your entries are correct”)
End Try
End Sub
End Class
Calling the object method
Calling “Set” property procedures
Creating the object
Calling “Get”
property procedure
110-I 29
Instance Members And Shared MembersMembers include both properties and methods
A shared member has ONE copy for ALL objects of the class
No need to instantiate an object to access the shared members (property or method), just use the Class Name
ex. Color.Red
A instance member has ONE copy for EACH object or instance of the class
Class Name
Property Name
Use the Shared Keyword to create a Shared Member
110-I 30
Instance versus Shared Members
• Instance Members– Separate memory location for each instance
of the object
• Shared Members– Single memory location that is available for
ALL objects of a class– Can be accessed without instantiating an object
of the class– Use the Shared keyword to create
110-I 31
Creating Shared Members
Use the Shared Keyword to create a Shared Member
Example.
Private Shared mdecSalesTax As Decimal
Shared ReadOnly Property SalesTax( ) As Decimal
Get
Return mdecSalesTax
End Get
End Property Make shared properties Read-Only, so their valuescan be retrieved but not set directly
[Public|Private] Shared Function FunctionName (ArgumentList) _As Datatype
110-I 32
The KeyWord Me• An instance method of a class is always called using an
instance of the class (an object), Object.Method(Arguments);
• The instance object is not part of the actual parameter list. However, it is still passed to the method implicitly.
• It can't appear in the formal parameter list
• To refer to the object used to make the call, use the keyword Me.
110-I 33
Using The KeyWord Me An example(1)• In an instance method, access the object implicitly passed to that
method with the me keyword. Public class SomeClass
private var As Integer Public Sub changeVar(n As Integer)
Me.var = n ‘OK, but superfluous End SubEnd Class
• Could also do Public Sub changeVar(var As Integer)
Me.var = var End Sub
var is local to changeVar. Since the name is the same as the instance variable var, we need to use Me to refer to the instance variable var (potentially confusing).The local variable shadows the instance variable.
110-I 34
Using The KeyWord Me An example(2)• In an instance method, any reference to an instance variable or any call to another
instance method done without an explicit reference uses the implicit object(me). Public class Bar
Public Sub foo1() ‘ codeEnd SubPublic Sub foo2()
foo1(); ‘call the instance method foo1 ‘ of the implicit object.
‘ same as Me.foo1(); End SubEnd Class
110-I 35
Constructors and Destructors• Constructor
– Method that automatically executes when an object is instantiated
– Create by writing a Public Sub New procedure
• Destructor– Method that automatically executes when an object is
destroyed
– Create by writing a Finalize procedure
– Usage discouraged by Microsoft
110-I 36
Overloading
• Overloading means that 2 or more methods have the same name but a different list of arguments (the signature)
• Create by giving the same name to multiple procedures in your class module, each with a different argument list
110-I 37
Parameterized Constructor
• Constructor that requires arguments
• Arguments are passed when an object is instantiated
• Can be used to assign initial property values
110-I 38
More on Constructors
Sub New()
‘Constructor with empty argument List
‘Initialize Instance Variables
End Sub
Sub New( Arguments)
‘Constructor with argument List
‘Use Arguments to initialize instance variables
End Sub
110-I 39
Example Using a Constructors
Sub New( ByVal Title As String, ByVal Quantity As Integer, ByVal Price As Decimal)
‘Use Arguments to initialize instance variables
Me.Title=Title
Me.Quantity=Quantity
Me.Price=Price
End Sub
Call to the Set Property Procedure
Set the value using the argument
110-I 40
References and assignment (1)• Consider
Public Sub SomeSales() ‘ create two objects
mBookSale1 = New BookSale() mBookSale2 = New BookSale()
‘ Set title, quantity and price mBookSale1.Quantity=5 mBookSale2.Quantity=10 mBookSale1.Price=2 mBookSale2.Price=3
mBookSale2= mBookSale1‘ Calculate the cost of each sale and display it
lblDisplay1.Text= mBookSale1.ExtendedPrice() lblDisplay2.Text= mBookSale2.ExtendedPrice()
End Sub
• What happens?
110-I 41
References and assignment (2)
• Before executing mBookSale2 = mBookSale1
mBookSale1:BookSale
mBookSale2:BookSale
mBookSale1 = mBookSale2
:BookSale
mBookSale2:BookSaleX
The object that mBookSale2 referred to can't be accessed anymore. The memory it uses is freed by the garbage collector.
The sale price is the same in both labels
Note: if 2 or more references refer to the same object, drop the object reference in the UML notation
mBookSale1
mBookSale2
mBookSale1
mBookSale2
110-I 42
Garbage Collection• Feature of .NET Common Language Runtime
(CLR) that cleans up unused components• Periodically checks for un-referenced objects and
releases all memory and system resources used by the objects
• Microsoft recommends depending on Garbage Collection rather than Finalize procedures