Visual Basic .NET Programming
Classes and Objects * Property of STI Page 1 of 9
TOPIC TITLE: Classes and Objects Specific Objectives: At the end of the topic session, the students are expected to: Cognitive:
1. Determine the procedures for defining a class. 2. Use access modifiers in defining a class. 3. Declare methods and properties of a class. 4. Discuss the supporting events with objects. 5. Compare different kinds of objects. 6. Discuss object-oriented programming with structures and
modules.
Affective:
1. Listen to others with respect. 2. Participate in class discussions actively.
MATERIALS/EQUIPMENT:
o topic slides o OHP
TOPIC PREPARATION:
o Have the students research on the following: � Classes and objects � Structures � Modules
o It is imperative for the instructor to incorporate various kinds of teaching strategies while discussing the suggested topics. The instructor may use the suggested learning activities below to facilitate a thorough and creative discussion of the topic.
o Prepare the slides to be presented in the class.
TOPIC PRESENTATION: The topic will revolve around the overview of classes and objects. This will be the suggested flow of discussion for the course topic:
1. Introduce to the students the topics to be covered in this session.
2. Ask the students to share their research about class. 3. Define and give example of a class. 4. Ask the students to give their own example of a class. 5. Discuss the procedures for defining a class. 6. Determine the different access modifiers that can be used for a
class. 7. Discuss the syntax in declaring methods and properties of a
class. 8. Define and discuss objects. 9. Call students to cite differences between class and
structures/modules. 10. Remind the students that they will have a quiz next meeting.
Visual Basic .NET Programming
Classes and Objects * Property of STI Page 2 of 9
Classes and Objects Page 1 of 16
Visual Basic .Net Programming
Classes and Objects * Property of STIPage 1 of 16
Classes and Objects
� Define Class
� Procedures for Defining a Class
� Using Access Modifiers
� Declaring Methods
� Declaring Properties
� Define Objects
� Supporting Events with Objects
� Comparing Objects
� OOP with Structures and Modules
Classes and Objects These are the topics to be discussed under the Classes and Objects:
o Define Class - Procedures for Defining a Class - Using Access Modifiers - Declaring Methods - Declaring Properties
o Define Objects - Supporting Events with Objects - Comparing Objects
o OOP with Structures and Modules [Classes and Objects, Page 1 of 16]
Class Page 2 of 16
Visual Basic .Net Programming
Classes and Objects * Property of STIPage 2 of 16
Class
� defines a new type of thing
� defines the common characteristics of every object of that new type
� in defining a new class, the characteristics
of all objects of that class, as well as their behaviors are defined
� declaring class:
Class NewClass
‘ statement
End Class
Class
A class defines a new type of thing. It defines the common characteristics of every object of that new type. For example, you want to define a class Flower. Every flower will share certain characteristics (stamen, stigma, petals, and so forth). A rose, jasmine, and sampaguita belong to the class Flower; they are of type Flower.
An object is an individual instance of a class. In the example above, they are the rose, jasmine, and sampaguita. Objects will be discussed later in the topic.
When defining a new class, the characteristics of all objects of that class, as well as their behaviors are defined. In VB.NET, the characteristics were described with member fields, also known as properties`. Member fields are variables declared with public scope in a class. The behavior of the new type was defined with methods, which contain codes to perform an action.
A class in VB.NET is declared using the keyword Class and enclosed
with the End Class marker.
Example:
Class NewClass
‘ statement
End Class
where NewClass is the name of the new data type or class we are
defining. [Class, Page 2 of 16]
Visual Basic .NET Programming
Classes and Objects * Property of STI Page 3 of 9
Procedure for Defining a Class Page 3 of 16
Visual Basic .Net Programming
Classes and Objects * Property of STIPage 3 of 16
Procedure forDefining a Class
� To define a class
� Add a class to the project
� Provide an appropriate name of the class
� Create constructors as needed
� Create a destructor if appropriate
� Declare properties
� Declare methods and events
Procedure for Defining a Class This is the general procedure in defining a class:
• Add a class to the project.
• Provide an appropriate file name of the class. This will name both the class and the file itself. If the file name is not changed when it is added to the project, the class name can be changed at any time by changing the class definition in the code window.
• Create constructors as needed.
• Create a destructor if appropriate.
• Declare properties.
• Declare methods and events.
NOTE: Constructors and destructors will be discussed in the next topic. [Procedure for Defining a Class, Page 3 of 16]
Using Access Modifiers Pages 4 of 16
Visual Basic .Net Programming
Classes and Objects * Property of STIPage 4 of 16
UsingAccess Modifiers
� Access Modifiers
� specify accessibility of variables and
procedures
The union of Protected
and Friend.
Protected Friend
Only for use on class
members.
Protected
Accessible only within
the type itself and all
namespaces and code
with the same assembly.
Friend
Accessible only within
the type itself.
Private
Accessible everywherePublic
DefinitionKeyword
Using Access Modifiers Access Modifiers can be used to specify the scope of the variables and procedures in the class that is defined. The table below describes the five access modifiers that is used in VB.NET:
Access Modifier Definition
Public Accessible everywhere.
Private Accessible only within the type itself.
Friend Accessible only within the type itself and all namespaces and code with the same assembly.
Protected Only for use on class members. Accessible within the class itself and any derived classes.
Protected Friend The union of Protected and Friend. Accessible to code within the same assembly and to any derived classes regardless of the assembly to which they belong.
[Using Access Modifiers, Page 4 of 16]
Declaring Methods Page 5 of 16
Visual Basic .Net Programming
Classes and Objects * Property of STIPage 5 of 16
DeclaringMethods
� Methods
� procedures that contain application logic
� Syntax:
Public Sub TestIt(ByVal x As
Integer) …
End Sub
Public Function GetIt( ) As
Integer
…
End Function
Declaring Methods Methods are procedures that contain application logic. They can either be sub or function procedures. The syntax to declare a method is as follows:
Public Sub TestIt(ByVal x As Integer)
…
End Sub
Public Function GetIt( ) As Integer
…
End Function
Example:
Dim iSum As Integer = 0
Visual Basic .NET Programming
Classes and Objects * Property of STI Page 4 of 9
Public Sub PerformAdd(ByVal iAdd As Integer)
iSum = iSum + iAdd
End Sub
Public Function GetSum(ByVal i As Integer) As
Integer
iSum = iSum + i
Return iSum
End Function
In PerformAdd method, the iSum integer variable was computed by
adding its current value to the iAdd method parameter.
In GetSum method, the iSum integer variable was computed by adding
its current value to the i method parameter and return as GetSum
value. [Declaring Methods, Page 5 of 16]
Declaring Properties Page 6 of 16
Visual Basic .Net Programming
Classes and Objects * Property of STIPage 6 of 16
DeclaringProperties
� Properties
� used to store variables in a class
� Syntax
Public Property MyData( ) As
Integer
Get
Return intMyData
End Get
Set (ByVal Value As Integer)
intMyData = Value
End Set
End Property
Declaring Properties Properties are used to store variables in a class. It exists to give an object-oriented way of setting and getting variables. The syntax to declare class properties are in VB.NET differs significantly from VB6. In VB6, properties are created by declaring two separate procedures: for Get and for Let or Set. In VB.NET, properties are
declared by using two code blocks in a single procedure as follows:
[Default| ReadOnly|WriteOnly] Property name
varname ([parameter list]) [As typename]
Get
[ block]
End Get
Set (ByVal Value As typename)
[block]
End Set
End Property
Example:
Public Property MyData( ) As Integer
Get
Return intMyData
End Get
Set (ByVal Value As Integer)
intMyData = Value
End Set
End Property
In the example, it shows how a property MyData of type integer was
declared. The Get block returns an unseen local variable called
Visual Basic .NET Programming
Classes and Objects * Property of STI Page 5 of 9
Declaring Properties Page 7 of 16
Visual Basic .Net Programming
Classes and Objects * Property of STIPage 7 of 16
DeclaringProperties
� ReadOnly Properties
� used to get the value of the property
� can be created by using ReadOnly keyword
� cannot be used in an assignment statement
� Example:
Public ReadOnly Property MyData( )
As Integer
Get
Return intMyData
End Get
End Property
Declaring Properties Page 8 of 16
Visual Basic .Net Programming
Classes and Objects * Property of STIPage 8 of 16
DeclaringProperties
� Write-Only properties
� used to set the value of the property
� can be created by using WriteOnly keyword
� cannot be used to retrieve the value of the
property
� Example:
Public WriteOnly Property
MyData( ) As Integer
Set (ByVal Value As Integer)
intMyData = Value
End Set
End Property
Declaring Properties Page 9 of 16
Visual Basic .Net Programming
Classes and Objects * Property of STIPage 9 of 16
DeclaringProperties
� Default property
� can be created by using the Default keyword
� must be coded to take at least one argument
� public, protected, or friend access must be specified
� property array � a property that is indexed
� Example:
[Default Public Property Item(ByVal index As Integer) As Boolean
Get
Return myArray(index)
End Get
Set (ByVal Value As Boolean)
myArray(index) = Value
End Set
End Property
intMyData by using a Return statement. The Set block uses the
Value parameter to store the passed-in property value to the
intMyData local variable. Using Read-Only Properties
Read-Only properties are used to get the value of the property. Read-
Only properties can be created by using ReadOnly keyword when
property will be declared. Read-Only properties cannot be used in an
assignment statement. Here is an example showing how to specify this property:
Public ReadOnly Property MyData( ) As Integer
Get
Return intMyData
End Get
End Property
Set block cannot be used when defining read-only properties because
the property cannot be updated. An error will be generated if it is done in the program. Using Write-Only Properties Write-Only properties are used to set the value of the property.
Write-Only properties can be created by using WriteOnly keyword
when property will be declared. Write-Only properties cannot be used
to retrieve the value of the property. Here is an example showing how to specify this property:
Public WriteOnly Property MyData( ) As Integer
Set (ByVal Value As Integer)
intMyData = Value
End Set
End Property
Get block cannot be used when defining write-only properties because
the property is not readable. An error will be generated if it is done in the program. Using Default Properties
Default property for a class can be created by using the Default
keyword when property will be declared. The property must be coded to take at least one argument, public, protected, or friend access must be specified. One limitation of default property is that, for a property to be default it must be a property array. A property array is a property that is indexed--- much like an array. An example is the Item property on a collection or list object. Here is an example showing how to specify this property: [Default Public Property Item(ByVal index As Integer)
As Boolean
Get
Return myArray(index)
Visual Basic .NET Programming
Classes and Objects * Property of STI Page 6 of 9
End Get
Set (ByVal Value As Boolean)
myArray(index) = Value
End Set
End Property
The example shows how to declare a default property that takes an index as an argument and returns a Boolean value. [Declaring Properties, Pages 6-9 of 16]
Objects Pages 10 of 16
Visual Basic .Net Programming
Classes and Objects * Property of STIPage 10 of 16
Objects
� an individual instance of a class
� a usable example of the thing the class represents
Objects An object is an individual instance of a class. It is a usable example of the thing the class represents. Other examples of object aside from the one mentioned above, are silk, cotton, etc., under the class Cloth, or mango tree, coconut tree, etc., under the class Tree. In .NET everything is an object, and objects are instances of classes, so we can say that everything is a class. [Objects, Page 10 of 16]
Supporting Events with Objects Page 11 of 16
Visual Basic .Net Programming
Classes and Objects * Property of STIPage 11 of 16
Supporting Events with Objects
� To define and support events using Event
statement:
[<attrlist>][ Public | Private |
Protected | Friend | Protected
Friend]
[ Shadows ] Event
eventname[(arglist)]
[Implements
interfacename.interfaceeventnam]
Supporting Events with Objects Events are notifications that cause something to happen or occur in response to something happening. To define and support events using Event statement:
[<attrlist>][ Public | Private | Protected | Friend |
Protected Friend]
[ Shadows ] Event eventname[(arglist)]
[Implements interfacename.interfaceeventname]
where:
attrlist – list of attributes that apply to this event. Commas are
used to separate multiple attributes. Public | Private | Protected | Friend | Protected
Friend – access modifiers
Shadows – indicates that this event shadows an identically named
programming element in a base class.
eventname – name of the event.
interfacename – name of an interface.
Visual Basic .NET Programming
Classes and Objects * Property of STI Page 7 of 9
Supporting Events with Objects Page 12 of 16
Visual Basic .Net Programming
Classes and Objects * Property of STIPage 12 of 16
Supporting Events with Objects
� Example:
Public Class TripleClicker
Public Event trpClick(ByVal Text As
String)
Public Sub Click()
Static intCount As integer = 0
intCount += 1
If intCount >= 3 Then
intCount = 0
RaiseEvent trpClick_
(“The button was triple_
clicked.”)
EndIf
End Sub
End Class
Supporting Events with Objects Page 13 of 16
Visual Basic .Net Programming
Classes and Objects * Property of STIPage 13 of 16
Supporting Events with Objects
� Example (con’t)
Public Class Form1
Dim WithEvents Click3 As New TripleClicker
Private Sub Click3_trpClick(ByVal text As
String) Handles Click3.trpClick
TextBox1.Text = text
End Sub
Private Sub Button1_Click(ByVal sender As
System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
Click3.Click()
End Sub
End Class
interfaceeventname – name of the event being implemented.
Example:
Public Class TripleClicker
Public Event trpClick(ByVal Text As String)
Public Sub Click()
Static intCount As Integer = 0
intCount += 1
If intCount >= 3 Then
intCount = 0
RaiseEvent trpClick _
("The button was triple clicked.")
End If
End Sub
End Class
In the example, a new method, Click, was used to keep track of the
number of times a button is clicked. When the button is clicked three times, the trpClick event was raised, passing it the message “The
button was triple clicked.”
To put this new event to work, the Events example creates an object named Click3 that uses the WithEvents keyword so that VB knows
that we want this object to be able to handle events. Add the following code in the form class. Dim WithEvents Click3 As New TripleClicker
When the user clicks the button, we can keep track of the number of clicks with the Click method: Dim WithEvents Click3 As New TripleClicker
Private Sub Button1Click(ByVal sender As_
System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
Click3.Click()
End Sub
After the user clicks the button three times, the trpClick event occurs. To handle that event, we need an event handler, where we display the event’s message in a text box. Private Sub Click3_trpClick(ByVal text As_ String)
Handles Click3.trpClick
TextBox1.Text = Text
End Sub
The complete code for the Form is given below. Note
that the form contains a button named Button1 and a
text box named TextBox1.
Public Class Form1
Dim WithEvents Click3 As New TripleClicker
Private Sub Click3_trpClick(ByVal text As
String) Handles Click3.trpClick
Visual Basic .NET Programming
Classes and Objects * Property of STI Page 8 of 9
TextBox1.Text = text
End Sub
Private Sub Button1_Click(ByVal sender As
System.Object, ByVal e As System.EventArgs)
Handles Button1.Click
Click3.Click()
End Sub
End Class
[Supporting Events with Objects, Pages 11-13 of 16]
Comparing Objects Page 14 of 16
Visual Basic .Net Programming
Classes and Objects * Property of STIPage 14 of 16
Comparing Objects
� Is keyword
� a special keyword that can be used to compare objects in If statements
� Example:
Public Sub Button_Click(ByVal sender
As_ System.Object, ByVAl e As
System.EventArgs)
If sender Is Button1 Then
TextBox1.Text = “Button 1_
was clicked.”
Else
TextBox1.Text = “Button 2_
was clicked.”
EndIf
End Sub
Comparing Objects Is keyword is a special keyword that can be used to compare objects in
If statements. If the two objects that will be checked are the same
object, Is returns a True value.
Example:
Public Sub Button1_Click(ByVal sender As_
System.Object, ByVAl e As System.EventArgs) _
Handles Button1.Click
If sender Is Button1 Then
TextBox1.Text = “Button 1 was clicked.”
Else
TextBox1.Text = “Button 2 was clicked.”
End If
End Sub
In the example, a generic Click event handler for buttons
Button1_Click is provided. The actual button that caused the event is
passed in the sender argument, so which button was clicked was determined even if the event handler handles multiple buttons. [Comparing Objects, Page 11 of 16]
OOP with Structures and Modules Page 15 of 16
Visual Basic .Net Programming
Classes and Objects * Property of STIPage 15 of 16
OOP with Structures and Modules
� Structures
� similar to classes but without methods
� Differences between Structures and
Classes
� structure members cannot be declared as
Protected
� structures cannot inherit from other
structures
� cannot use the Finalize method
� structure cannot include initializers, the
New keyword, or set initial sizes of arrays
� cannot define a constructor that takes no
arguments for a structure
� default access of data members in
structures is public if structures were
declared with Dim
� when a data item created from a structure
to procedure was passed, the entire
structure was copied
OOP with Structures and Modules Structures are half-way solution between variables and true objects, allowing creating a new data types. They are like classes without methods. Structures can also support methods. In fact it can be created as how a class is created, except that Structure keyword was used instead of Class. Here are some of the differences between Structures and Classes:
• Structure members cannot be declared as Protected
• Structures cannot inherit from other structures.
• Cannot use the Finalize method.
• The declarations of data members in a structure cannot include initializers, the New keyword, or set initial sizes of arrays.
• Cannot define a constructor that takes no arguments for a structure unless you make a constructor shared.
• If structures were declared with Dim, the default access of data members in structures is public (not private as in classes and modules).
• When a data item created from a structure to procedure was passed, the entire structure was copied.
Visual Basic .NET Programming
Classes and Objects * Property of STI Page 9 of 9
OOP with Structures and Modules Page 16 of 16
Visual Basic .Net Programming
Classes and Objects * Property of STIPage 16 of 16
OOP with Structures and Modules
� Modules
� holds code, but can also support members,
like classes
� has exactly one instance and does not need
to be created or assigned to a variable
� do not support inheritance or implement
interfaces
� Differences between Modules and Classes
� members of a module are implicitly shared
� modules can never be instantiated
� modules do not support inheritance
� modules cannot implement interfaces
� modules cannot be nested in other types
Modules are designed to hold code, but can also support members, like classes. A module is almost synonymous to a class but with some significant distinctions. A module has exactly one instance and does not need to be created or assigned to a variable. Unlike a class, modules do not support inheritance or implement interfaces. Inheritance and interfaces will be discussed in succeeding topics. Differences between Modules and Classes:
• The members of a module are implicitly shared.
• Modules can never be instantiated, which means that objects can’t be created based on them.
• Modules do not support inheritance.
• Modules cannot implement interfaces.
• Modules cannot be nested in other types. [OOP with Structures and Modules, Pages 15-16 of 16]
EVALUATION/GENERALIZATION:
• A class is a template. It defines the common characteristics of every object of that new type.
• An object is an instance of a class.
• A class is composed of class members and properties where the members define the behavior of the class and the properties the attributes of the class.
• Access modifiers are used to define the scope of the class as well as class members and properties.
• Is keyword can be used to compare objects in If statements.
• Structures and Modules are also used in object-oriented programming (OOP).
• A module has the same lifetime as your program.
• Structures are like classes without methods.
REFERENCES:
� Microsoft Official Course, (2002), 2373B: Programming with Microsoft Visual Basic .NET, Microsoft Corporation
� Holzner, Steven, (2003), Sams teach yourself Microsoft Visual Basic.Net 2003 in 21 days, USA, Sams Publishing
� Liberty, Jesse, (2003), Learning Visual Basic .NET, USA, O'Reilly & Associates, Inc