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

We begin with an example that consists of classes GradeBook (Fig. 4.1) and GradeBookTest (Fig. 4.2). Class GradeBook (declared in file GradeBook.cs) will be used to display a message on the screen (Fig. 4.2) welcoming the instructor to the grade-book application. Class GradeBookTest (declared in the file GradeBookTest.cs) is a testing class in which the Main method will create and use an object of class GradeBook. By convention, we declare classes GradeBook and GradeBookTest in separate files, such that each file's name matches the name of the class it contains.

Figure 4.1. Class declaration with one method.

(This item is displayed on page 132 in the print version)

 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 public void DisplayMessage()
 9 {
10 Console.WriteLine( "Welcome to the Grade Book!" );
11 } // end method DisplayMessage
12 } // end class GradeBook

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

(This item is displayed on page 133 in the print version)

 1 // Fig. 4.2: GradeBookTest.cs
 2 // Create a GradeBook object and call its DisplayMessage method.
 3
 4 public class GradeBookTest
 5 {
 6 // Main method begins program execution
 7 public static void Main( string[] args )
 8 {
 9 // create a GradeBook object and assign it to myGradeBook
10 GradeBook myGradeBook = new GradeBook();
11
12 // call myGradeBook's DisplayMessage method
13 myGradeBook.DisplayMessage();
14 } // end Main
15 } // end class GradeBookTest
 
Welcome to the Grade Book!

To start, select File > New Project... to open the New Project dialog, then create a GradeBook Console Application. Delete all the code provided automatically by the IDE and replace it with the code in Fig. 4.1.

Class GradeBook

The GradeBook class declaration (Fig. 4.1) contains a DisplayMessage method (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 message. (We do this in Fig. 4.2.)

The class declaration begins in line 5. The keyword public is an access modifier. For now, we simply declare every class public. Every class declaration contains keyword class followed 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 class GradeBook.

In Chapter 3, each class we declared had one method named Main. Class GradeBook also has one methodDisplayMessage (lines 811). Recall that Main is a special method that is always called automatically when you execute an application. Most methods do not get called automatically. As you will soon see, you must call method DisplayMessage to tell it to perform its task.

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. Keyword voidknown as the method's return typeindicates that this method will not return (i.e., give back) any information to its calling method when it completes its task. When a method that specifies a return type other than void is 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 balance, you expect the ATM to give you back a value that represents your balance. If you have a method Square that returns the square of its argument, you would expect the statement

int result = Square( 2 );

to return 4 from method Square and assign 4 to variable result. If you have a method Maximum that returns the largest of three integer arguments, you would expect the statement

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

to return the value 114 from method Maximum and assign the value to variable biggest. You have already used methods that return informationfor example, in Chapter 3 you used Console method ReadLine to input a string typed by the user at the keyboard. When ReadLine inputs a value, it returns that value for use in the application.

The name of the method, DisplayMessage, follows the return type (line 8). By convention, method names begin with an uppercase first letter, and all subsequent words in the name begin with a capital letter. 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 does not require additional information to perform its task. Line 8 is commonly referred to as the method header. Every method's body is delimited by left and right braces, as in lines 9 and 11.

The body of a method contains statement(s) 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 class GradeBook in an application. As you learned in Chapter 3, method Main begins the execution of every application. Class GradeBook cannot begin an application because it does not contain Main. This was not a problem in Chapter 3, because every class you declared had a Main method. To fix this problem for the GradeBook, we must either declare a separate class that contains a Main method or place a Main method in class GradeBook. To help you prepare for the larger applications you will encounter later in this book and in industry, we use a separate class (GradeBookTest in this example) containing method Main to test each new class we create in this chapter.

Adding a Class to a Visual C# 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 > New Item... from the pop-up menu. In the Add New Item dialog that appears, select Code File and enter the name of your new filein this case, GradeBookTest.cs. A new, blank file will be added to your project. Add the code from Fig. 4.2 to this file.

Class GradeBookTest

The GradeBookTest class declaration (Fig. 4.2) contains the Main method that controls our application's execution. Any class that contains a Main method (as shown in line 7) can be used to execute an application. This class declaration begins in line 4 and ends in line 15. The class contains only a Main method, which is typical of many classes that simply begin an application's execution.

Lines 714 declare method Main. A key part of enabling the method Main to begin the application's execution is the static keyword (line 7), which indicates that Main is a static method. A static method 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 explain static methods in Chapter 7, Methods: A Deeper Look.

In this application, we'd 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, as shown in line 10. We begin by declaring variable myGradeBook. 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 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 an extensible language.

Variable myGradeBook (line 10) is initialized with the result of the object creation expression new GradeBook(). The new operator creates a new object of the class specified to the right of the keyword (i.e., GradeBook). The parentheses to the right of the GradeBook are required. As you will learn in Section 4.9, 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 will 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 use myGradeBook to call its method DisplayMessage. Line 13 calls the method DisplayMessage (lines 811 of Fig. 4.1) using variable myGradeBook followed by a dot operator (.), 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 a console windoweach of those method calls provided arguments that specified the data to display. At the beginning of line 13, "myGradeBook." indicates that Main should use the GradeBook object that was created on line 10. The empty parentheses in line 8 of Fig. 4.1 indicate that method DisplayMessage does not require additional information to perform its task. For this reason, the method call (line 13 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, method Main continues executing at line 14. This is the end of method Main, so the application 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.17 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#. 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 C#. The UML models operations by listing the operation name followed by a set of parentheses. Class GradeBook has one method, DisplayMessage, so the bottom compartment of Fig. 4.3 lists one operation with this name. Method DisplayMessage does not require additional information to perform its tasks, so there are empty parentheses following DisplayMessage in 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 that DisplayMessage is a public operation in the UML (i.e., a public method in C#). The plus sign is sometimes called the public visibility symbol. 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.

(This item is displayed on page 134 in the print version)


Declaring a Method with a Parameter

Preface

Index

    Introduction to Computers, the Internet and Visual C#

    Introduction to the Visual C# 2005 Express Edition IDE

    Introduction to C# Applications

    Introduction to Classes and Objects

    Control Statements: Part 1

    Control Statements: Part 2

    Methods: A Deeper Look

    Arrays

    Classes and Objects: A Deeper Look

    Object-Oriented Programming: Inheritance

    Polymorphism, Interfaces & Operator Overloading

    Exception Handling

    Graphical User Interface Concepts: Part 1

    Graphical User Interface Concepts: Part 2

    Multithreading

    Strings, Characters and Regular Expressions

    Graphics and Multimedia

    Files and Streams

    Extensible Markup Language (XML)

    Database, SQL and ADO.NET

    ASP.NET 2.0, Web Forms and Web Controls

    Web Services

    Networking: Streams-Based Sockets and Datagrams

    Searching and Sorting

    Data Structures

    Generics

    Collections

    Appendix A. Operator Precedence Chart

    Appendix B. Number Systems

    Appendix C. Using the Visual Studio 2005 Debugger

    Appendix D. ASCII Character Set

    Appendix E. Unicode®

    Appendix F. Introduction to XHTML: Part 1

    Appendix G. Introduction to XHTML: Part 2

    Appendix H. HTML/XHTML Special Characters

    Appendix I. HTML/XHTML Colors

    Appendix J. ATM Case Study Code

    Appendix K. UML 2: Additional Diagram Types

    Appendix L. Simple Types

    Index



    Visual C# How to Program
    Visual C# 2005 How to Program (2nd Edition)
    ISBN: 0131525239
    EAN: 2147483647
    Year: 2004
    Pages: 600

    Similar book on Amazon

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