Instantiating Objects
To make an actual instance of Dog, you must declare the object and you must allocate memory for the object. You declare an object much as you declare a variable of a primitive type.
Dim milo as Dog 'declare a Dog object
The declaration shown doesn't actually create an instance, however. To create an instance of a class you must allocate memory for the object by using the keyword New:
milo = New Dog() 'allocate memory for milo
You typically combine the declaration and the creation of the new instance into a single line:
Dim milo As New Dog()
This declares milo to be an object of type Dog, and creates a new instance of Dog. You'll see what the parentheses are for later in this chapter when we discuss the constructor.
In Visual Basic 2005, everything happens within a class. "But wait!" I hear you cry, "Don't we create modules?" Yes, Visual Studio .NET does create modules, but when you compile your application, a class is created for you from that module. This allows Visual Studio .NET to continue to use modules (as Visual Basic did) but still comply with the .NET approach that everything is a class.
No methods can run outside of a class, not even Main, the entry point for your program. Typically, you'll create a small module to house Main:
Module modMain
Public Sub Main()
...
End Sub
End ModuleThe compiler will turn this into a class for you. A somewhat more efficient alternative is for you to declare the class yourself:
Public Class Tester Public Sub Main() Dim testObject ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access