JavaScript Editor
JavaScript Debugger|
| ||
As discussed in the In Depth section of this chapter, as well as in Chapter 2, constructors are special methods that let you configure the objects you create from a class. We've already dealt with constructors throughout this book, as in this code from Chapter 5, where we're passing data to the constructors for the Size and Point classes:
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim TextBox1 As New TextBox()
TextBox1.Size = New Size(150, 20)
TextBox1.Location = New Point(80, 20)
TextBox1.Text = "Hello from Visual Basic"
Me.Controls.Add(TextBox1)
End Sub
So how do you create a constructor? You add a Sub procedure named New to a class—that's all it takes. For example, here's how that might look for the class named DataClass which we saw in the In Depth section of this chapter; in this case, I'm storing the value passed to New in a private data member named value:
Public Class DataClass
Private value As Integer
Public Sub New(ByVal newValue As Integer)
value = newValue
End Sub
Public Function GetData() As Integer
Return value
End Function
End Class
Now I can store the value 5 inside an object of the DataClass class simply by passing 5 to the constructor:
Dim data As New DataClass(5)
MsgBox(data.GetData())
Note that all classes have a default constructor that doesn't take any arguments; this constructor exists so you can create objects without providing an explicit New Sub procedure and doesn't do anything special. (However, if you derive a new class from a base class and add a constructor to the derived class, Visual Basic will complain if you don't call the base class's constructor from the derived class's constructor and there's no explicit base class constructor that takes no arguments.) More on constructors is coming up in the next chapter, when we start deriving classes from base classes.
|
| ||
Free JavaScript Editor
JavaScript Editor