18.2. 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 Module 

The 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 As New Tester(  )    End Sub    ' other members End Class 

In this example, you create the class Tester explicitly. Even though Tester was created to house the Main method, you've not yet instantiated any objects of type Tester. To do so, you would write:

 Dim testObject As New Tester(  ) 'make an instance of Tester 

Creating an instance allows you to call other methods on testObject, as you'll see later in this chapter.



Programming Visual Basic 2005
Programming Visual Basic 2005
ISBN: 0596009496
EAN: 2147483647
Year: 2006
Pages: 162
Authors: Jesse Liberty

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net