c# class.method

Upload: sargunam-sankaravadivel

Post on 03-Apr-2018

215 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/29/2019 c# Class.method

    1/5

    4.3 Declaring a Class with a Method and Instantiating an Object ofa 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 amessage on the screen (Fig. 4.2) welcoming the instructor to the grade-book application.

    ClassGradeBookTest(declared in the fileGradeBookTest.cs) is a testing class in which

    theMainmethod will create and use an object of classGradeBook. By convention, we

    declare classesGradeBookandGradeBookTestin separate files, such that each file's name

    matches the name of the class it contains.

    Fig 4.1. Class declaration with one method.

    1 // Fig. 4.1: GradeBook.cs

    2 // Class declaration with one method.

    3 using System;4

    5public class GradeBook

    6 {

    7 // display a welcome message to the GradeBook user

    8 public voidDisplayMessage()

    9 {

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

    11 } // end method DisplayMessage

    12 } // end class GradeBook

    Fig 4.2. Create a GradeBook object and call its DisplayMessage method.

    1 // Fig. 4.2: GradeBookTest.cs

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

    3public class GradeBookTest

    4 {

    5 // Main method begins program execution

    6 public static voidMain( string[] args )

    7 {

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

    9 GradeBook myGradeBook = new GradeBook();

    10

    11 // call myGradeBook's DisplayMessage method

    12 myGradeBook.DisplayMessage();

    13 } // end Main

    14 } // end class GradeBookTest

    Welcome to the Grade Book!

    To start, selectFile > New Project...to open theNew Projectdialog, then create aGradeBookConsole

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

  • 7/29/2019 c# Class.method

    2/5

    Class GradeBook

    TheGradeBookclass declaration(Fig. 4.1) contains aDisplayMessagemethod (lines 811) that

    displays a message on the screen. Line 10 of the class displays the message. Recall that a class is

    like a blueprintwe need to make an object of this class and call its method to get line 10 to execute

    and display its messagewe do this in Fig. 4.2.

    The class declaration begins in line 5. The keywordpublicis anaccess modifier. Access

    modifiers determine the accessibility of an object's properties and methods to other methods in an

    application. 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.

    In Chapter 3, each class we declared had one method namedMain. ClassGradeBookalso has one

    methodDisplayMessage(lines 811). Recall thatMainis a special method that's always called

    automatically when you execute an application. Most methods do not get called automatically. 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.

    Keywordvoidknown as the method'sreturn typeindicates that this method willnotreturn (i.e.,

    give back) any information to itscalling methodwhen it completes its task. When a method that

    specifies a return type other thanvoidis called and completes its task, the method returns a result toits calling method. For example, when you go to an automated teller machine (ATM) and request your

    account 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

    int result = Square( 2 );

    to return4from methodSquareand assign4to variableresult. If you have a methodMaximumthat

    returns the largest of three integer arguments, you'd expect the statement

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

    to return the value114from methodMaximumand assign the value to variablebiggest. You've

    already used methods that return informationfor example, in Chapter 3 you

    usedConsolemethodReadLineto input a string typed by the user at the keyboard.

    WhenReadLineinputs a value, itreturnsthat value for use in the application.

    The name of the method,DisplayMessage, follows the return type (line 8). Generally, methods are

    named asverbsorverb phraseswhile classes are named asnouns. By convention, 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 Pascal case. The parentheses after the method name

  • 7/29/2019 c# Class.method

    3/5

    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. Every method's body is delimited by left and right braces, as in lines 9 and 11.

    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.

    Next, we'd like to use classGradeBookin an application. As you learned in Chapter 3,

    methodMainbegins the execution of every application. ClassGradeBookcannot begin an application

    because it does not containMain. This was not a problem in Chapter 3, because every class you

    declared had aMainmethod. To fix this problem for theGrade-Book, we must either declare a

    separate class that contains aMainmethod or place aMainmethod in classGradeBook. To help you

    prepare for the larger applications 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 application. 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 click theAddbutton. A new blank file will be added to your project. Add the

    code from Fig. 4.2 to this file.

    Class GradeBookTest

    TheGradeBookTestclass declaration (Fig. 4.2) contains theMainmethod that controls our

    application's execution. Any class that contains aMainmethod (as shown in line 6) can be used to

    execute an application. 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 application's execution.

    Lines 613 declare methodMain. A key part of enabling the methodMainto begin the application's

    execution is thestatickeyword (line 6), which indicates thatMainis astaticmethod.

    Astaticmethod is special because it can be called without first creating an object of the class (in this

    case,GradeBookTest) in which the method is declared. We explainstaticmethods in Chapter 7,

    Methods: A Deeper Look.

    In this application, we'd like to call classGradeBook'sDisplayMessagemethod 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, as shown in line 9. We begin by declaring

  • 7/29/2019 c# Class.method

    4/5

    variablemyGradeBook. The variable's type isGradeBookthe class we declared in Fig. 4.1. Each new

    class you create becomes a new type in C# that can be used to declare variables and create objects.

    New class types will be accessible to all classes in the same project. You can declare new class types

    as needed; this is one reason why C# is known as anextensible language.

    VariablemyGradeBook(line 9) is initialized with the result of theobject-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 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.

    We can now usemyGradeBookto call its methodDisplayMessage. Line 12 calls the

    methodDisplayMessage(lines 811 of Fig. 4.1) using variablemyGradeBookfollowed by amember

    access (.) operator, the method nameDisplayMessageand an empty set of parentheses. 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 windoweach of those method calls

    provided arguments that specified the data to display. At the beginning of line 12, "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, methodMaincontinues

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

    UML Class Diagram for Class GradeBook

    Figure 4.3presents aUML class diagramfor classGradeBookof Fig. 4.1. Recall from Section

    1.15 that the UML is a graphical language used by programmers 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 and properties in C#. InFig. 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 correspond to methods in C#. The UML models

    operations by listing the operation name followed by a set of parentheses. ClassGradeBookhas one

    method,DisplayMessage, so the bottomcompartment ofFig. 4.3lists one operation with this name.

    MethodDisplayMessagedoes not require additional information to perform its tasks, so there are

    empty parentheses followingDisplayMessagein the class diagram, just as they appeared in the

    http://popup%28%27/content/images/chap4_9780132151429/elementLinks/04fig03.jpg')http://popup%28%27/content/images/chap4_9780132151429/elementLinks/04fig03.jpg')http://popup%28%27/content/images/chap4_9780132151429/elementLinks/04fig03.jpg')http://popup%28%27/content/images/chap4_9780132151429/elementLinks/04fig03.jpg')http://popup%28%27/content/images/chap4_9780132151429/elementLinks/04fig03.jpg')http://popup%28%27/content/images/chap4_9780132151429/elementLinks/04fig03.jpg')
  • 7/29/2019 c# Class.method

    5/5

    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 thepublicvisibility symbol. We'll often use UML class diagrams to

    summarize a class's attributes and operations.

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

    http://popup%28%27/content/images/chap4_9780132151429/elementLinks/04fig03.jpg')http://popup%28%27/content/images/chap4_9780132151429/elementLinks/04fig03.jpg')http://popup%28%27/content/images/chap4_9780132151429/elementLinks/04fig03.jpg')http://popup%28%27/content/images/chap4_9780132151429/elementLinks/04fig03.jpg')