Classes and Objects Fields, Properties, Methods, and Events Class vs. Object Members Abstraction, Encapsulation, Inheritance, and Polymorphism Overloading, Overriding, and Shadowing Constructors and Destructors An OOP Example Structures and Modules Immediate Solutions: Creating Classes Creating Objects Creating Structures Creating Modules Creating Constructors Using Is to Compare Objects Creating Data Members Creating Class (Shared) Data Members Creating Methods Creating Class (Shared) Methods Creating Properties Creating Class (Shared) Properties Creating Events Creating Class (Shared) Events Overloading Methods and Properties Getting Rid of Objects When You're Done with Them Triggering Garbage Collection Creating Class Libraries Creating Namespaces Using the Finalize Method (Creating Destructors)
Just about everything you do in Visual Basic .NET involves objects in some way—even simple variables are based on the Visual Basic Object class. And all your code has to appear in a class of some sort, even if you're using a module or structure, which are also types of classes now. For these reasons, it's important to understand object-oriented programming (OOP) in Visual Basic, and now more than ever before. This and the following chapter are dedicated to OOP.
We haven't looked at OOP in detail until now, because we didn't really need to understand a great deal of the programming aspect of it. Visual Basic comes with thousands of built-in classes, ready to use, so we didn't have to plumb the depths too much. We knew that Windows forms are classes, of course, based on the System.Windows.Forms.Form class, and that our code was part of that class:
Public Class Form1 Inherits System.Windows.Forms.Form Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ⋮ End Sub End Class
And we knew, too, that controls such as text boxes are really based on classes, as with the TextBox class, as in this example from Chapter 5, CreateTextBox, where we created a new object of that class and used that object's various members to configure it:
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
But that's just a start. To go further, we're going to have to create our own classes and objects.