Initializing Class Member Variables
When you create a class object, you will normally immediately assign values to specific class member variables.
For example, the following code fragment defines a Person class that contains fields for a Name, Age, OfficeNumber, and CellularPhoneNumber:
Class Person
Public Name As String
Public Age As Integer
Public OfficeNumber As String
Public CellularPhoneNumber As String
End Class
Within your program, you can create (instantiate) instances of the Person class, which programmers refer to as objects, using the following statement:
Dim thePerson As New Person ()
To simplify the process of initializing class member variables, you can place a special subroutine within your class definition (named New) that Visual Basic .NET automatically calls each time you create a class object.
Programmers refer to this special subroutine as a “constructor” because it helps
you build (construct) the class object.
The constructor method is special in that within any class definition, the constructor is always named New.
Programmers use the constructor to initialize class member variables.
The following code fragment, for example, extends the Person class to include the New constructor method:
Class Person
Public Name As String
Public Age As Integer
Public OfficeNumber As String
Public CellularPhoneNumber As String
Sub New(ByVal PesonName As String, ByVal PersonAge As Integer, _
ByVal PersonOfficeNumber As String, _
ByVal PersonCellularPhoneNumber As String)
Name = PesonName
Age = PersonAge
OfficeNumber = PersonOfficeNumber
CellularPhoneNumber = PersonCellularPhoneNumber
MsgBox("Name: " & PesonName & " Age: " & PersonAge & _
" OfficeNumber: " & PersonOfficeNumber & _
“CellularPhoneNumber:” & PersonCellularPhoneNumber )
End Sub
End Class
Well, I made a windows application sample using messagebox to display the results.
I attached the sample files on this article.
I hope the article helps to you.
'Visual Basic .NET > Class' 카테고리의 다른 글
A destructor method in a class (0) | 2008.06.26 |
---|---|
using MyBase (0) | 2008.06.25 |
understand the inherited constructors of class (0) | 2008.06.25 |
how about using Multiple Constructors to Support Different Parameters (0) | 2008.06.24 |
How to Restrict Access to Class Members? (0) | 2008.06.23 |