Section 4.3. Declaring a Class with a Method and Instantiating an Object of a Class


4.3. Declaring a Class with a Method and Instantiating an Object of a Class

We begin with an example that consists of class GradeBook (Fig. 4.1) and module GradeBookTest (Fig. 4.2). Class GradeBook (declared in file GradeBook.vb) displays a message on the screen (Fig. 4.2) welcoming the instructor to the grade-book application. Module GradeBookTest (declared in file GradeBookTest.vb) contains the Main method that instantiates (creates) and uses an object of class GradeBook. The class and module are placed in separate files for clarity, but it is possible to place them in the same file.

Figure 4.1. Class declaration with one method.

 1  ' Fig. 4.1: GradeBook.vb 2  ' Class declaration with one method. 3  Public Class GradeBook 4     ' display a welcome message to the GradeBook user 5     Public Sub DisplayMessage() 6        Console.WriteLine("Welcome to the Grade Book!") 7     End Sub ' DisplayMessage 8  End Class ' GradeBook 

Figure 4.2. Creating an object of class GradeBook and calling its DisplayMessage method.

  1  ' Fig. 4.2: GradeBookTest.vb  2  ' Create a GradeBook object and call its DisplayMessage method.  3  Module GradeBookTest  4     ' Main begins program execution  5     Sub Main()  6        ' initialize gradeBook to refer to a new GradeBook object  7        Dim gradeBook As New GradeBook()  8  9        ' call gradeBook's DisplayMessage method 10        gradeBook.DisplayMessage() 11     End Sub ' Main 12  End Module ' GradeBookTest 

 Welcome to the Grade Book! 



Adding a Class to a Visual Basic Project

For each example in this chapter, you will add a class to your console application. To do this, right click the project name in the Solution Explorer and select Add > Class... from the menu that appears. In the Add New Item dialog that appears, enter the name of your new file, in this case GradeBook.vb. A new file will be added to your project with an empty GradeBook class. Add the code from Fig. 4.1 to this filewe'll discuss this code shortly.

Class GradeBook

The GradeBook class declaration (Fig. 4.1) contains a DisplayMessage method (lines 57) that displays a message on the screen. Recall that a class is like a blueprintwe need to make an object of class GradeBook and call its method to get line 6 to execute and display its message. We do this in the Main method in Fig. 4.2.

The class declaration begins at line 3. The keyword Public is an access modifier. For now, we will simply declare every class Public. Every class declaration contains keyword Class followed immediately by the class's name. Every class's body ends with the keywords End Class, as in line 8 of class GradeBook.

Method DisplayMessage

Class GradeBook has one methodDisplayMessage (lines 57). The method declaration begins with keyword Public to indicate that the method is "available to the public"that is, it can be called from outside the class declaration's body by methods of other classes or modules (these other classes and modules are called clients of the class). Keyword Sub indicates that this method will perform a task but will not return (i.e., give back) any information to its calling method when it completes its task. You have already used methods that return informationfor example, in Chapter 3 you used Console method ReadLine to input an integer typed by the user at the keyboard. When ReadLine inputs a value, it returns that value for use in the program.

The name of the method, DisplayMessage, follows keyword Sub. By convention, method names begin with an uppercase letter and all subsequent words in the name begin with a capital letter (recall that Visual Basic is not case sensitive). The parentheses after the method name are used to indicate any parametersadditional information that is required by the method to perform its task (we discuss parameters in more detail in Section 4.4). An empty set of parentheses, as in line 5, indicates that this method does not require any additional information and does not need any parameters. We refer to the part of the method in line 5 as the method header. Like Main, method DisplayMessage ends with keywords End Sub.

The body of a method contains statements that perform the method's task. In this case, the method contains one statement (line 6) that displays the message "Welcome to the Grade Book!" in the Console window. After this statement executes, the method has completed its task.

Note that the DisplayMessage method declaration is similar to the declaration of Main. We discuss methods in depth in Chapter 7, Methods: A Deeper Look.

In Chapter 3, each module we declared had one method named Main. Class GradeBook, likewise, has one method. Recall that Main is a special method that is required to begin the execution of every application. Main is called automatically by the runtime when you execute an application.

Using Class GradeBook

We will now use class GradeBook in an application. A Visual Basic project that contains only class GradeBook is not an application that can be executed because GradeBook does not contain Main. If you try to compile such a project, you will get the error message:

'Sub Main' was not found in 'GradeBook.GradeBookTest'.


This was not a problem in Chapter 3, because every application you created contained a Main method. To fix this problem for the GradeBook, either we must declare a separate class or module that contains Main, or we must place Main in class GradeBook. We use a separate module (GradeBookTest in this example) containing Main to test each new class we create in this chapter.

Module GradeBookTest

The GradeBookTest module declaration (Fig. 4.2; lines 312) contains the Main method (lines 511) that controls our application's execution. The module contains only a Main method, which is typical of many modules that begin an application's execution.

Lines 511 declare method Main. In this application, we would like to call class GradeBook's DisplayMessage method to display the welcome message in the Console window. Typically, you cannot call a method that belongs to another class until you create an object of that class. We begin by declaring variable gradeBook (line 7). Note that the variable's type is GradeBookthe class we declared in Fig. 4.1. Each new class you create becomes a new type in Visual Basic that can be used to declare variables and create objects. Programmers can declare new class types as needed; this is one reason why Visual Basic is known as an extensible language.

Variable gradeBook is initialized with the result of the object creation expression New GradeBook() (Fig. 4.2; line 7). Operator New creates a new object of the class specified to the right of the New keyword (i.e., GradeBook). The class name is followed by a set of parentheses. As you'll see in Section 4.7, those parentheses in combination with a class name represent a call to a constructor, a special type of method that is used only when an object is created to initialize the object's data. In that section you will see that arguments can be placed in the parentheses to specify initial values for the object's data. In this example, we simply leave the parentheses empty. When there are no arguments to be placed in the parentheses, Visual Basic allows for the parentheses to be omitted, as in the next example. Although Visual Basic is not case sensitive, it does allow us to create objects (e.g., gradeBook) with the "same" name as their class (e.g. GradeBook)we do this throughout the book.

We can now use object gradeBook to call method DisplayMessage. Line 10 calls DisplayMessage (declared in lines 57 of Fig. 4.1) using variable gradeBook followed by a dot separator (.), the method name DisplayMessage and an empty set of parentheses. This call causes the DisplayMessage method to perform its task. This method call differs from the method calls in Chapter 3 that displayed information in the Console windoweach of those method calls provided arguments that specified the data to display. At the beginning of line 10, "gradeBook. " indicates that Main should use the object of class GradeBook that was created in line 7. The empty parentheses in line 5 of Fig. 4.1 indicate that method DisplayMessage has no parametersthat is, DisplayMessage does not require additional information to perform its task. For this reason, the method call (line 10 of Fig. 4.2) specifies an empty set of parentheses after the method name to indicate that no arguments are being passed to method DisplayMessage. When method DisplayMessage completes its task, Main continues executing at line 11, which is the end of method Main, so the program terminates.

UML Class Diagram for Class GradeBook

Figure 4.3 presents a UML class diagram for class GradeBook of Fig. 4.1. Recall from Section 1.9 that the UML is a graphical language that programmers use to represent their object-oriented systems in a standardized manner. In the UML, each class is modeled in a class diagram as a rectangle with three compartments. The top compartment contains the name of the class centered horizontally in boldface type. The middle compartment contains the class's attributes, which correspond to instance variables in Visual Basic. In Fig. 4.3, the middle compartment is empty because the version of class GradeBook in Fig. 4.1 does not have any attributes. The bottom compartment contains the class's operations, which correspond to methods in Visual Basic. The UML models an operation by listing its name followed by a set of parentheses. Class GradeBook has one method, DisplayMessage, so the bottom compartment of Fig. 4.3 lists the operation with this name. Method DisplayMessage does not require additional information to perform its tasks, so the parentheses following DisplayMessage in the class diagram are empty, just as they were in the method's declaration in line 5 of Fig. 4.1. The plus sign (+) in front of the operation name indicates that DisplayMessage is a public operation in the UML (because it is a Public method in Visual Basic). We will often use UML class diagrams to summarize a class's attributes and operations.

Figure 4.3. UML class diagram indicating that class GradeBook has a public DisplayMessage operation.




Visual BasicR 2005 for Programmers. DeitelR Developer Series
Visual Basic 2005 for Programmers (2nd Edition)
ISBN: 013225140X
EAN: 2147483647
Year: 2004
Pages: 435

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