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

Một phần của tài liệu Visual C 2012 How to Program _ www.bit.ly/taiho123 (Trang 149 - 154)

2. When the app executes, another compiler (known as the just-in-time compiler

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

We begin with an example that consists of classesGradeBook(Fig. 4.1) andGradeBook-

Test(Fig. 4.2). ClassGradeBook(declared in fileGradeBook.cs) will be used to display a

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

message on the screen (Fig. 4.2) welcoming the instructor to the grade-book app. Class

GradeBookTest(declared in the fileGradeBookTest.cs) is a testing class in which theMain method will create and use an object of classGradeBook. By convention, we declare classes

GradeBookandGradeBookTestin separate files, such that each file’s name matches the name of the class it contains.

To start, selectFile > New Project... to open the New Project dialog, then create a

GradeBookConsole Application. Rename theProgram.csfile toGradeBook.cs. Delete all the code provided automatically by the IDE and replace it with the code in Fig. 4.1.

ClassGradeBook

TheGradeBookclass declaration(Fig. 4.1) contains aDisplayMessagemethod (lines 8–

11) that displays a message on the screen. Line 10 of the class displays the message. Recall that a class is like a blueprint—we need to make an object of this class and call its method to get line 10 to execute and display its message—we do this in Fig. 4.2.

The class declaration begins in line 5. The keyword publicis an access modifier.

Access modifiers determine the accessibility of an object’s properties and methods to other methods in an app. For now, we simply declare every classpublic. Every class declaration contains keywordclassfollowed by the class’s name. Every class’s body is enclosed in a pair of left and right braces ({and}), as in lines 6 and 12 of classGradeBook.

Declaration of MethodDisplayMessage

In Chapter 3, each class we declared had one method namedMain. ClassGradeBookalso has one method—DisplayMessage(lines 8–11). Recall thatMainis a special method that’s always called automatically when you execute an app. Most methods donotget called au- tomatically. As you’ll soon see, you must call methodDisplayMessageto tell it to perform its task.

The method declaration begins with keywordpublicto 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. Keywordvoid—known as the method’sreturn type—indi- cates that this method will not return (i.e., give back) any information to its calling methodwhen it completes its task. When a method that specifies a return type other than

voidis called and completes its task, the method returns a result to its calling method. For example, when you go to an automated teller machine (ATM) and request your account 1 // Fig. 4.1: GradeBook.cs

2 // Class declaration with one method.

3 using System;

4

5 public class GradeBook 6 {

7 // display a welcome message to the GradeBook user 8

9 {

10 Console.WriteLine( "Welcome to the Grade Book!" );

11 } // end method DisplayMessage 12 } // end class GradeBook

Fig. 4.1 | Class declaration with one method.

public void DisplayMessage()

balance, you expect the ATM to give you back a value that represents your balance. If you have a methodSquarethat returns the square of its argument, you’d expect the statement

to return4from methodSquareand assign4to variableresult. If you have a method

Maximumthat returns the largest of three integer arguments, you’d expect the statement to return the value114from methodMaximumand assign the value to variablebiggest. You’ve already used methods that return information—for example, in Chapter 3 you usedConsolemethodReadLineto input a string typed by the user at the keyboard. When

ReadLineinputs a value, itreturnsthat value for use in the app.

Method Name

The name of the method,DisplayMessage, follows the return type (line 8). Generally, methods are named asverbsorverb phraseswhile classes are named asnouns. By conven- tion, method names begin with an uppercase first letter, and all subsequent words in the name begin with an uppercase letter. This naming convention is referred to as upper camel case. The parentheses after the method name indicate that this is a method. An empty set of parentheses, as shown in line 8, indicates that this method doesnotrequire additional information to perform its task. Line 8 is commonly referred to as themethod header. Ev- ery method’s body is delimited by left and right braces, as in lines 9 and 11.

Method Body

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

Using ClassGradeBook

Next, we’d like to use classGradeBookin an app. As you learned in Chapter 3, method

Mainbegins the execution of every app. ClassGradeBookcannot begin an app because it does not containMain. This was not a problem in Chapter 3, because every class you de- clared had aMainmethod. To fix this problem for theGradeBook, we must either declare a separate class that contains aMainmethod or place aMainmethod in classGradeBook. To help you prepare for the larger apps you’ll encounter later in this book and in industry, we use a separate class (GradeBookTestin this example) containing methodMainto test each new class we create in this chapter.

Adding a Class to a Visual C# Project

For each example in this chapter, you’ll add a class to your console app. To do this, right click the project name in theSolution Explorerand selectAdd > New Item…from the pop- up menu. In theAdd New Itemdialog that appears, selectCode File, enter the name of your new file (GradeBookTest.cs) then clickAdd. A new blank file will be added to your proj- ect. Add the code from Fig. 4.2 to this file.

int result = Square( 2 );

int biggest = Maximum( 27, 114, 51 );

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

ClassGradeBookTest

TheGradeBookTestclass declaration (Fig. 4.2) contains theMainmethod that controls our app’s execution. Any class that contains aMainmethod (as shown in line 6) can be used to execute an app. This class declaration begins in line 3 and ends in line 14. The class contains only aMainmethod, which is typical of many classes that simply begin an app’s execution.

MainMethod

Lines 6–13 declare methodMain. A key part of enabling the method Mainto begin the app’s execution is thestatic keyword (line 6), which indicates that Mainis a static method. Astaticmethod is special because it can be called without first creating an ob- ject of the class (in this case,GradeBookTest) in which the method is declared. We explain

staticmethods in Chapter 7, Methods: A Deeper Look.

Creating aGradeBookObject

In this app, we’d like to call classGradeBook’sDisplayMessagemethod to display the wel- come message in the console window. Typically, you cannot call a method that belongs to another class until you create an object of that class, as shown in line 9. We begin by de- claring variablemyGradeBook. The variable’s type isGradeBook—the class we declared in Fig. 4.1. Each new class you create becomes a newtypein C# that can be used to declare variables and create objects. New class types will be accessible to all classes in the same proj- ect. You can declare new class types as needed; this is one reason why C# is known as an extensible language.

Variable myGradeBook (line 9) is initialized with the result of the object-creation expressionnew GradeBook(). Thenewoperator creates a new object of the class specified to the right of the keyword (i.e.,GradeBook). The parentheses to the right of theGrade-

Bookare required. As you’ll learn in Section 4.10, those parentheses in combination with a class name represent a call to a constructor, which is similar to a method, but is used only 1 // Fig. 4.2: GradeBookTest.cs

2 // Create a GradeBook object and call its DisplayMessage method.

3 public class GradeBookTest 4 {

5 // Main method begins program execution 6 public static void Main( string[] args )

7 {

8 // create a GradeBook object and assign it to myGradeBook 9

10

11 // call myGradeBook's DisplayMessage method 12

13 } // end Main

14 } // end class GradeBookTest

Welcome to the Grade Book!

Fig. 4.2 | Create aGradeBookobject and call itsDisplayMessagemethod.

GradeBook myGradeBook = new GradeBook();

myGradeBook.DisplayMessage();

at the time an object is created to initialize the object’s data. In that section you’ll see that data can be placed in parentheses to specify initial values for the object’s data. For now, we simply leave the parentheses empty.

Calling theGradeBookObject’sDisplayMessageMethod

We can now usemyGradeBookto call its methodDisplayMessage. Line 12 calls the meth- odDisplayMessage (lines 8–11 of Fig. 4.1) using variable myGradeBook followed by a member access (.) operator, the method nameDisplayMessageand an empty set of pa- rentheses. This call causes theDisplayMessagemethod to perform its task. This method call differs from the method calls in Chapter 3 that displayed information in a console window—each of those method calls provided arguments that specified the data to dis- play. At the beginning of line 12 (Fig. 4.2), “myGradeBook.” indicates thatMainshould use theGradeBookobject that was created in line 9. The empty parentheses in line 8 of Fig. 4.1 indicate that methodDisplayMessagedoes not require additional information to perform its task. For this reason, the method call (line 12 of Fig. 4.2) specifies an empty set of parentheses after the method name to indicate that no arguments are being passed to methodDisplayMessage. When methodDisplayMessagecompletes its task, method

Maincontinues executing at line 13. This is the end of methodMain, so the app terminates.

UML Class Diagram for ClassGradeBook

Figure 4.3 presents a UML class diagram for class GradeBook of Fig. 4.1. Recall from Section 1.6 that the UML is a graphical language used by programmers to represent their ob- ject-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 and properties in C#. In Fig. 4.3, the middle compartment is empty because the version of classGradeBookin Fig. 4.1 does not have any attributes. The bottom compartment contains the class’s operations, which cor- respond to methods in C#. The UML models operations by listing the operation name fol- lowed by a set of parentheses. ClassGradeBookhas one method,DisplayMessage, so the bottom compartment of Fig. 4.3 lists one operation with this name. MethodDisplayMes- sagedoes not require additional information to perform its tasks, so there are empty paren- theses followingDisplayMessagein the class diagram, just as they appeared in the method’s declaration in line 8 of Fig. 4.1. The plus sign (+) in front of the operation name indicates thatDisplayMessageis a public operation in the UML (i.e., apublicmethod in C#). The plus sign is sometimes called thepublic visibility symbol. We’ll often use UML class dia- grams to summarize a class’s attributes and operations.

Fig. 4.3 | UML class diagram indicating that classGradeBookhas apublic DisplayMessageoperation.

GradeBook + DisplayMessage( )

Một phần của tài liệu Visual C 2012 How to Program _ www.bit.ly/taiho123 (Trang 149 - 154)

Tải bản đầy đủ (PDF)

(1.020 trang)