- A Simple Temperature Conversion Program
- Building a Temperature Class
- Putting the Decisions into the Temperature Class
- Using Classes for Format and Value Conversion
- A String Tokenizer Class
- Classes as Objects
- Class Initialization
- Classes and Properties
- Another Interface Example·The Voltmeter
- A vbFile Class
- Programming Style in Visual Basic
- Summary
Classes and Properties
Classes in VB can have Property methods as well as public and private functions and subs. These correspond to the kinds of properties you associate with Forms, but they can store and fetch any kinds of values you care to use. For example, rather than having methods called getAge and setAge, you could have a single Age property that then corresponds to a Property Let and a Property Get method.
Property Get age() As Integer age = sAge 'return the current age End Property '------ Property Let age(ag As Integer) sAge = ag 'save a new age End Property
To use these properties, you refer to the Let property on the left side of an equals sign and the Get property on the right side.
myAge = sw.Age 'Get this swimmer's age sw.Age = 12 'Set a new age for this swimmer
Properties are somewhat vestigial, since they really applied more to Forms, but many programmers find them quite useful. They do not provide any features not already available using get and set methods, and both generate equally efficient code.
In the revised version of our SwimmerTimes display program, we convert all of the get and set methods to properties and then allow users to vary the times of each swimmer by typing in new ones. Here is the Swimmer class.
Option Explicit Private frname As String, lname As String Private sClub As String Private sAge As Integer Private tms As New Times Private place As Integer '------ Public Sub init(dataline As String) Dim tok As New Tokenizer tok.init dataline 'initilaize string tokenizer place = Val(tok.nextToken) 'get lane number frname = tok.nextToken 'get first name lname = tok.nextToken 'get last name sAge = Val(tok.nextToken) 'get age sClub = tok.nextToken 'get club tms.setText tok.nextToken 'get and parse time End Sub '------ Property Get time() As String time = tms.getFormatted End Property '------ Property Let time(tx As String) tms.setText tx End Property '------ Property Get Name() As String 'combine first and last names and return together Name = frname & " " & lname End Property '------ Property Get age() As Integer age = sAge 'return the current age End Property '------ Property Let age(ag As Integer) sAge = ag 'save a new age End Property '------ Property Get Club() As String Club = sClub End Property
Then when the txTime text entry field loses focus, we can store a new time as follows.
Private Sub txTime_Change() Dim i As Integer Dim sw As Swimmer i = lsSwimmers.ListIndex 'get index of list If i >= 0 Then Set sw = swimmers(i) 'get that swimmer sw.time = txTime.Text 'store that time End If End Sub