- 4.1 Introduction
- 4.2 Classes, Objects, Methods, Properties and Instance Variables
- 4.3 Declaring a Class with a Method and Instantiating an Object of a Class
- 4.4 Declaring a Method with a Parameter
- 4.5 Instance Variables and Properties
- 4.6 UML Class Diagram with a Property
- 4.7 Software Engineering with Properties and set and get Accessors
- 4.8 Auto-Implemented Properties
- 4.9 Value Types vs. Reference Types
- 4.10 Initializing Objects with Constructors
- 4.11 Floating-Point Numbers and Type decimal
- 4.12 Wrap-Up
- Summary
- Terminology
- Self-Review Exercises
- Answers to Self-Review Exercises
- Exercises
- Making a Difference Exercises
4.3 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 GradeBook-Test (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.
Fig 4.1. Class declaration with one method.
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
|
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. 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 |
To start, select File > New Project... to open the New Project dialog, then create a GradeBook Console Application. Rename the Program.cs file to GradeBook.cs. 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 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 public is an access 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 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 method—DisplayMessage (lines 8–11). Recall that Main is 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 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 void—known as the method's return type—indicates 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'd expect the statement
|
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'd expect the statement
|
to return the value 114 from method Maximum and assign the value to variable biggest. You've already used methods that return information—for 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). Generally, methods are named as verbs or verb phrases while classes are named as nouns. 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 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 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 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 Grade-Book, 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'll 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'll 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, enter the name of your new file (GradeBookTest.cs) then click the Add button. 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 6) can be used to execute an application. This class declaration begins in line 3 and ends in line 14. The class contains only a Main method, which is typical of many classes that simply begin an application's execution.
Lines 6–13 declare method Main. A key part of enabling the method Main to begin the application's execution is the static keyword (line 6), 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 9. We begin by declaring variable myGradeBook. The variable's type is GradeBook—the 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 9) 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 Grade-Book are 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 use myGradeBook to call its method DisplayMessage. Line 12 calls the method DisplayMessage (lines 8–11 of Fig. 4.1) using variable myGradeBook followed by a member access (.) 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 window—each of those method calls provided arguments that specified the data to display. At the beginning of line 12, "myGradeBook." indicates that Main should use the GradeBook object that was created in line 9. 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 12 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 13. 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.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#. 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 bottomcompartment 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'll often use UML class diagrams to summarize a class's attributes and operations.
Fig. 4.3 UML class diagram indicating that class GradeBook has a public DisplayMessage operation.