VB Lecture Notes - Classes
Objective #1: Use the Object Browser and API to explore existing classes and objects.
- The teacher will demonstrate how to use the Visual Basic Object Browser.
- You can learn how to use the default classes that come with VB by reading VB's API. API stands for application program interface. An API is like a user manual for
a programming language. It lists & explains the names of classes, their methods and their properties. An API is available for practically any programming language. Often, a programming language's
API can be found on the Web.
Objective #2: Design your own class.
- A class is created so that objects from that class can be used throughout one or more programs. The existence of classes allows the concept of reusability
to be extended even further than just reusing methods and functions. In fact a class is really just a set of related methods that can be reused in programs written by other people.
- The name of a class should always be capitalized as in Bug not bug. Since classes represent objects which are usually
nouns, the name of a class is usually a noun.
- A class includes properties and methods. Methods are the actions (i.e. verbs) that an object can "do" while properties are the characteristics
of an object.
- Properties are included in a class so that the object variables made from that class are realistic and allow for flexible programming. The complete set of properties of an object
and their values at any given moment during the execution of the program is called the state of an object.
- I recommend naming all properties with the prefix "my". For example, if a Bug object's weight is stored
in a property then the property should be named myWeight and not simply weight. It is not required in this VB course to use data type prefixes such as int in
the name of a property. So a property for the weight of a Bug can be named myWeight rather than myintWeight.
- It is a good idea to include a number of methods in a class so that it is easy for other programmers to use objects from that class. The complete set of methods for an object is
called the behavior of the object.
- A method should be named properly to describe the action that it represents. Often verbs are used as method names. For example, a method should be named move instead
of newPosition. Method names should begin with a lowercase letter.
- Some programmers jobs consist of solely creating classes and not really writing computer programs that end users actually execute. These programmers are called class developers.
- Some programmers write projects that make use of the other programmers' classes. These programmers are called client programmers. In our VB class, each student will
be his/her own class developer and client programmer. The VB form that declares an object from a class is called the client program.
- A class should be designed to be general enough for other people to use that class.
Objective #3: Create your own class.
- You begin creating a class by clicking the Project/Add Class menu command. This opens up a code window where you type all of the code for the class.
- A class named Bug would be contained inside of the statements
Public Class Bug
End Class
- A class should always be declared as Public rather than Private so that client programmers can use your class.
- Properties should be listed at the top of a class before the methods. There can be as many properties in a class as you want. Some programmers however list the properties at the
bottom of a class.
- Each property is declared on a line of code such as
Private myAge As Integer
where the name of the property is usually preceded by either Private or Public.
Do not use the keyword Dim to declare a property within a class. If the word Public is used then programmers
who use objects from your class, can directly change the value stored in a property. Properties are typically declared to be Private though
because making a property Public would make it too easy for a client programmer to mess up the value of a property. It is common and
considered good style for beginner programmers to use the prefix my in the names of properties. You do not have to use data type prefixes
though such as int or dbl.
- Do not set a property equal to zero or any other value in its declaration statement like you do with local variables in Dim statements.
- A class often as quite a few properties. There is no limit to how many properties that a class can include.
- You should add a default constructor to every class that you create. A default constructor is technically not method but you can think of it as a special method
that is called when a new object is declared and created anywhere in a program. Here is a default constructor for a Bug class that includes
the properties myAge and myWeight:
Public Sub New()
myAge = 0
myWeight = 10
End Sub
A default constructor is always Public rather than Private. The
name of a constructor must be New. Inside of a constructor, you typically type assignment statements that initialize the properties
of an object variable to desirable starting values. In the Bug example, it makes sense to initialize a bug's age to zero but since even a baby bug must weight something a logical value for
a bug's weight might be 10.
- In a client program the statement
Dim nemo As New Bug
would call the default constructor above and would declare and create a new Bug object. We call the creation of a new object instantiation.
That is another way to say "create an object" is to "instantiate an object". By the way, the legal statement
Dim nemo
would only declare a reference to an object and not actually create an object. Errors would occur if you used methods with nemo where he was only declared and not instantiated.
- It's a good idea to add another constructor besides the default constructor that allows the client programmer to pass one or more parameters to the constructor. I call this kind
of constructor an "other" constructor. The constructor below
Public Sub New(ByVal intWeight As Integer)
myAge = 0
myWeight = intWeight
End Sub
is passed the parameter intWeight which is then stored in the property myWeight. The following line of code in a client program would
call this "other" constructor
Dim willie As New Bug(20)
in which case the Bug object willie would have an initial weight of 20 but an age of 0.
- An accessor method should have a name that is similar to the property that it matches with except that you use a "get" prefix
instead of the "my" prefix. For example here is an accessor method for a Bug object's myWeight property:
Public Function getWeight() As Integer
Return myWeight
End Function
An accessor method must be public rather than private. That way, client programmers can use accessor methods to retrieve and make use of property values especially since
properties are almost always private. An accessor method must be a function since it returns a value.
This statement
MessageBox.Show(nemo.getWeight())
would display nemo's weight in a client program. Notice the necessary empty parenthesis after the method's name.
- A modifier method (aka mutator method) is the opposite of an accessor method. A modifier method allows a client programmer to change (i.e. modify)
a property value. The prefix "set" is commonly used with modifier methods.
Public Sub setWeight(ByVal intWeight As Integer)
myWeight = intWeight
End Sub
This statement
nemo.setWeight(30)
would be used in a client program to set the weight of the nemo object to the value 30.
A modifier method must be public, otherwise a client programmer couldn't use it. Modifier methods are useful since properties are usually private and cannot be directly modified by a client programmer.
You could add an If statement to keep a sloppy client programmer from storing an unreasonable value to a property as in this example:
Public Sub setWeight(ByVal intWeight As Integer)
If (intWeight > 0 And intWeight < 100) Then
myWeight = intWeight
Else
MessageBox.Show("Bug weight's must be between 0 and 100")
End If
End Sub
If the myWeight property was public then this kind of validation check could not be performed. You need to have the body of a modifier method to be able to add an If statement
like this.
- You can type many other methods in a class besides constructors, accessors, and modifiers so your object can have flexible behavior making it easy for client programmers to
work with. I call these "interesting" methods. For example, you could have a method named eat such as
Public Sub eat()
myWeight += 1
End Sub
which would be called in a client program with the statement
nemo.eat()
Of course a parameter could be passed to the eat method as in
Public Sub eat(ByVal intNum As Integer)
myWeight += intNum
End Sub
which could be called in a client program with the statement
nemo.eat(10)
You could also use an "interesting" method to return a value that is computed based on properties in of the object. Pretend a Bug's IQ is based on its age and weight.
Assume also that you didn't want to have separate myIQ property for some reason. So, in order to get a Bug's IQ, a client programmer
would need to call the available testIQ method.
Public Function testIQ() As Integer
Return Math.Pow(myAge, 2) / myWeight
End Function
The client program statement
MessageBox.Show(nemo.testIQ())
would display nemo's IQ in a message box.
Objective #4: Use objects from a class that you created in a client form.
- A form on which you want to use an object from a class that you created is called a client program.
- To use an object from a class that you created you must first declare and instantiate the object with a statement such as
Dim nemo As New Bug
using the keyword New in front of the name of the class. Not only does this line of code declare that nemo is a variable
name in the client program but it also instantiates the object variable by giving it memory space and initial values in its properties. The name of the object variable nemo could
be anything that you want to use. You do not have to use any kind of prefix with objects from classes that you created.
- A programmer could use the following line of code in a client form to overwrite a value in an object variable's property.
nemo.myWeight = 10
This statement stores the value 10 in the myWeight property of an object variable named nemo but only if the Bug class's myWeight property
was made Public. If the word Private was used to declare the myWeight property then the line above
would cause an error. In that case, the programmer would need to use a property method (aka modifier method) in order to change the value of the property. If a modifier method named setWeight was
added to the Bug class then the statement:
nemo.setWeight(10)
would make nemo's myWeight equal to the value 10.
- To retrieve and/or display the value stored in an object variable's property, you can use the statement
lblOutput.Text = nemo.myAge
if the property myAge is public. However, since it's bad style to make properties public, the following line of code would be used to display nemo's
age in a label on the client form
lblOutput.Text = nemo.getAge()
This line of code will only work if a public property method (aka accessor method) named age is included in the Bug class.
Objective #5: Create a child class to a class that you created.
Objective #6: Override a method in a child class.
- All public methods in a parent class are inherited by its child classes. But sometimes the child class wants one of these methods to work differently than it does in the parent class.
You can modify the way a method works in the child class by overriding the method.
- Every class (including your Bug class) inherits at least two methods from the Object class, the ToString method
and the Equals method. It is a wise idea to override each of these methods in every class that you develop and write. Client programmers who use your
class will expect that you overrided these methods in your class.
- The Equals function should be similar to this
Public Overrides Function Equals(ByVal Obj As Object) As Boolean
Dim other As New Bug
other = CType(Obj, Bug) ' cast Obj to a Bug
If (other.myWeight = Me.myWeight And other.myAge = Me.myAge) Then
Return True
Else
Return False
End If
End Function
where the class developer picks one (or more) properties of the class to use to determine whether two objects are equal to one another. The equals method is similar to
the CompareTo method in how it uses an Object parameter and casting. This statement in a client program
If (nemo.Equals(charlie)) Then
MessageBox.Show("They are equal")
End If
makes use of the Equals function. Notice that the Equals function is a function and not a regular method. It returns a Boolean value, True or False,
depending on whether the two objects are equal or not.
- The ToString function in a Bug class could look like this
Public Overrides Function ToString() As String
Return "weight = " + myWeight.ToString() + vbCrLf + "age = " + myAge.ToString()
End Function
The ToString method returns a string that shows the state of the object. That is, each property and the value of that property is concatenated into one string and returned
to the client program. This statement in a client program makes use of the ToString function
MessageBox.Show(nemo.ToString())
Usually the ToString function is only used by client programmers for debugging purposes.
- If a child class wants an inherited public method from a parent class to work differently than it does in the parent class, the child class can override that method
as long as it was marked as Overridable in the parent class. While it is good style to override the Equals and ToString methods
that are inherited from the Object class, you can override any method that is inherited from a parent class. Here is an example:
Public Class Bug
Public Overridable Sub eat()
MessageBox.Show("eating like a bug")
End Sub
End Class
Public Class LittleBug
Inherits Bug
Public Overrides Sub eat()
MessageBox.Show("eating like a little bug")
End Sub
End Class
- The idea that a method can be used in one way with regard to a parent class (such as Bug) and it can be used
in another way with regard to a child class (such as LittleBug) is called polymorphism. Polymorphism
means
"many shapes" and loosely refers to how a method can act in different ways.
Objective #7: Use composition to create more realistic classes.
- By adding a property to a class that has a data type that is another class is called composition. A PictureBox property called myBody is
added to the Bug class below. Since PictureBox is class this is an example of composition. The relationship between the Bug class and the PictureBox class is called a "has-a" relationship since
a Bug "has a" PictureBox.
- Suppose that there is a Location class with the following class definition
Public Class Location
Private myRow As Integer
Private myCol As Integer
Public Sub New()
myRow = 0
myCol = 0
End Sub
Public Sub New(ByVal intRow As Integer, ByVal intCol As Integer)
myRow = intRow
myCol = intCol
End Sub
Public Function getRow() As Integer
Return myRow
End Function
Public Function getCol() As Integer
Return myCol
End Function
End Class
Then the Bug class could have a Location object
as a property as in
Public Class Bug
Private myLocation as Location
Public Sub New()
myLocation = New Location(10, 20)
End Sub
Public Function getLocation() As Location
Return myLocation
End Function
Public Sub setLocation(ByVal newLocation As Location)
myLocation = newLocation
End Sub
End Class
and code such as this could be used in a client program to indicate where a bug named nemo is currently positioned....
MessageBox.Show("nemo is at the position " + nemo.getLocation().getRow() + ", " + nemo.getLocation().getCol())
- Here is a copy of a more complete Bug class without the CompareTo, ToString,
and Equals methods:
Public Class Bug
Private myWeight As Integer
Private myAge As Integer
Private myBody As New PictureBox
Public Sub New() ' default constructor
Dim dice As New Random
myWeight = 10
myAge = 0
myBody.Left = dice.Next(300) + 1
myBody.Top = dice.Next(300) + 1
myBody.SizeMode = PictureBoxSizeMode.AutoSize
myBody.Image = Image.FromFile(System.AppDomain.CurrentDomain.BaseDirectory()
" ..\images\Bug.gif")
End Sub
Public Function getPic() As PictureBox
Return myBody
End Function
' other accessors and modifiers here
Public Sub moveRight()
myBody.Image = Image.FromFile(System.AppDomain.CurrentDomain.BaseDirectory()
" ..\images\BugRight.gif")
myBody.Left += 10
End Sub
Public Sub moveLeft()
myBody.Image = Image.FromFile(System.AppDomain.CurrentDomain.BaseDirectory()
" ..\images\BugLeft.gif")
myBody.Left -= 10
End Sub
Public Sub die()
myBody.Top = 0 ' floating to the top
Threading.Thread.Sleep(2000) ' pausing for 2 seconds
myBody.Visible = False
End Sub
End Class
Objective #8: Add a CompareTo method to a class.
- It is wise to add a CompareTo method to the class that you created since it is standard for a class to have a CompareTo method.
Client programmers who use your class will expect the class to have a CompareTo method.
Public Function CompareTo(ByVal obj As Object) As Integer
Dim other As New Bug
other = CType(obj, Bug) ' cast Obj to a Bug
If (Me.myWeight < other.weight()) Then
Return -1
ElseIf (Me.myWeight > other.weight()) Then
Return 1
Else
Return 0 ' the two objects are equal
End If
End Function
The keyword Me is optional in the example above. When the statement
MessageBox.Show(nemo.CompareTo(charlie))
executes in a client program, nemo is the object on which the CompareTo method is being called. So nemo is represented
as Me in the example above. The Bug object charlie is passed as the parameter so "he"
is represented as the parameter obj. It is a requirement for the obj parameter to have the data type Object so
it is necessary to change obj into a Bug object. The act of changing an object of one data type into another data type is called casting.
The verb "to cast" means to change an object into another type of object. It is standard for a CompareTo method to return a negative value (usually -1)
if the object itself is less than the parameter object and to return a positive value (usually 1) if the parameter object is less than the object itself. A zero must be returned if the two
objects are equal. It is up to the class developer to decide what property or combination of properties in the class should be used to determine whether one object is less than or greater than
another object.
Objective #9: Add event handling to a class.
Objective #10: Create a Class Library.
Objective #11: Create a Web Service