Creating and Calling Constructors

As you saw in the example in Listing 3.3, you use the New keyword to create an instance of a class. The New keyword calls the constructor of the class. A class constructor describes how to initialize the properties and methods of the class. Every class has a default constructor that is automatically generated for you as a method called Sub New.

You can override this default constructor by adding your own procedure named Sub New. Constructors can take parameters and can also be overloaded so that you can create an instance of the class in several ways. Overloading means that there are multiple versions of the same method, each with different parameters. Visual Basic 2005 enables you to create constructors that take one or more parameters so that you can pass data when you create an instance of the class. To overload the constructor, you add multiple Sub New methods that take different parameters.

1. Add the constructors in Listing 3.4 to your Sentence class.

Listing 3.4. Adding two constructors to a class

Public Sub New()

TextValue = "Hello World! " End Sub

Public Sub New(ByVal myText as String)

TextValue = myText End Sub

The first constructor overrides the default parameterless constructor and assigns the text "Hello World" to the member variable, TextValue. If you instantiate the class without passing any text, "Hello World" will be the value of the Sentence class. The second constructor takes a string as a parameter and assigns the string to the member variable.

2. Replace the code in the Startup event handler of ThisDocument with the code in Listing 3.5.

Listing 3.5. Passing parameters to a constructor Dim Sentence1 As New Sentence()

Dim Sentence2 As New Sentence("This is my second sentence.") Me.Paragraphs(1).Range.InsertAfter( _ Sentence1.Text & Sentence2.Text)

Notice that when you type the open parenthesis after the word Sentence, IntelliSense lists the overloaded methods and displays the required parameter (myText As String) in method 2 of 2, as shown in Figure 3.2.

Private Sub Thi3D0cu1t1ent._Start.up (ByVal sender A3 Object, EyVal e As System.EventArgs) Handles He.Startup Dim Sentencel As New Sentence(

End Sub

Figure 3.2. IntelliSense displays a parameter required by the constructor of the Sentence class.

3. Press F5 to run the solution.

This time, when the solution runs, the value to be assigned to Sentence2 is passed to the constructor of the Sentence class when the class is instantiated. Although you could assign a value to the Text property of Sentence2 after it's instantiated (as shown in Listing 3.7), this example (Listing 3.5) uses the default value "Hello World!"

0 0

Post a comment