Initializing Objects with Constructors

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

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

4.10 Initializing Objects with Constructors

4.10 Initializing Objects with Constructors

As mentioned in Section 4.5, when aGradeBook(Fig. 4.7) object is created, its instance variablecourseNameis initialized tonullby default. This is also true of theprivatein- stance variable that the compiler creates for the auto-implementedCourseNameproperty discussed in Section 4.8. What if you want to provide a course name when you create a

GradeBookobject? Each class can provide aconstructorthat can be used toinitializean object of a class when the object is created. In fact, C# requires a constructor call forevery object that’s created. Thenewoperator calls the class’s constructor to perform the initial- ization. The constructor call is indicated by the class name, followed by parentheses. For example, line 11 of Fig. 4.8 first usesnewto create aGradeBookobject. The empty paren- theses after “new GradeBook()”indicate a callwithout argumentsto the class’s constructor.

The compiler provides apublicdefault constructorwithnoparameters in any class that does notexplicitlydefine a constructor, soeveryclass has a constructor. The default con- structor doesnotmodify the default values of the instance variables.

Custom Initialization with Constructors

When you declare a class, you can provide your own constructor (or several constructors, as you’ll learn in Chapter 10) to specify custom initialization for objects of your class. For example, you might want to specify a course name for aGradeBookobject when the object is created, as in

In this case, the argument "CS101 Introduction to C# Programming"is passed to the

GradeBookobject’s constructor and used to initialize theCourseName. Each time you cre- ate anewGradeBookobject, you can provide adifferentcourse name. The preceding state- ment requires that the class provide a constructor with astringparameter. Figure 4.12 contains a modifiedGradeBookclass with such a constructor.

GradeBook myGradeBook =

new GradeBook( "CS101 Introduction to C# Programming" );

1 // Fig. 4.12: GradeBook.cs

2 // GradeBook class with a constructor to initialize the course name.

3 using System;

4

5 public class GradeBook 6 {

7 // auto-implemented property CourseName implicitly created an 8 // instance variable for this GradeBook's course name

9 public string CourseName { get; set; } 10

11 12 13 14 15 16 17

Fig. 4.12 | GradeBookclass with a constructor to initialize the course name. (Part 1 of 2.)

// constructor initializes auto-implemented property // CourseName with string supplied as argument public GradeBook( string name )

{

CourseName = name; // set CourseName to name } // end constructor

Declaring a Constructor

Lines 13–16 declare the constructor for classGradeBook.A constructor must have the same name as its class. Like a method, a constructor specifies in its parameter list the data it re- quires to perform its task. When you usenewto create an object, you place this data in the parentheses that follow the class name. Unlike a method, a constructor doesn’t specify a return type, not evenvoid. Line 13 indicates that classGradeBook’s constructor has a pa- rameter callednameof typestring. In line 15, thenamepassed to the constructor is used to initialize auto-implemented propertyCourseNamevia itssetaccessor.

Initializing GradeBook Objects with a Custom Constructor

Figure 4.13 demonstrates initializingGradeBookobjects using this constructor. Lines 12–

13 create and initialize aGradeBookobject. The constructor of classGradeBookis called with the argument "CS101 Introduction to C# Programming"to initialize the course name. Theobject-creation expressionto the right of=in lines 12–13 returns a reference to the new object, which is assigned to variablegradeBook1. Lines 14–15 repeat this process for anotherGradeBookobject, this time passing the argument"CS102 Data Structures in C#"to initialize the course name forgradeBook2. Lines 18–21 use each object’sCourse-

Nameproperty to obtain the course names and show that they were indeed initialized when the objects were created. In Section 4.5, you learned that each instance (i.e., object) of a class contains its own copy of the class’s instance variables. The output confirms that each

GradeBookmaintains its own course name.

18 // display a welcome message to the GradeBook user 19 public void DisplayMessage()

20 {

21 // use auto-implemented property CourseName to get the 22 // name of the course that this GradeBook represents 23 Console.WriteLine( "Welcome to the grade book for\n{0}!",

24 CourseName );

25 } // end method DisplayMessage 26 } // end class GradeBook

1 // Fig. 4.13: GradeBookTest.cs

2 // GradeBook constructor used to specify the course name at the 3 // time each GradeBook object is created.

4 using System;

5

6 public class GradeBookTest 7 {

8 // Main method begins program execution 9 public static void Main( string[] args )

10 {

Fig. 4.13 | GradeBookconstructor used to specify the course name at the time each

GradeBookobject is created. (Part 1 of 2.)

Fig. 4.12 | GradeBookclass with a constructor to initialize the course name. (Part 2 of 2.)

4.10 Initializing Objects with Constructors 127

Normally, constructors are declaredpublic. If a class does notexplicitlydefine a con- structor, the class’s instance variables are initialized to their default values—0 for numeric types,falsefor typeboolandnullfor reference types. If you declare any constructors for a class, C# willnotcreate a default constructor for that class.

Adding the Constructor to ClassGradeBook’s UML Class Diagram

The UML class diagram of Fig. 4.14 models classGradeBookof Fig. 4.12, which has a constructor that has anameparameter of typestring. Like operations, the UML models constructors in the third compartment of a class in a class diagram. To distinguish a con- structor from a class’s operations, the UML places the word “constructor” between guil- lemets (ô and ằ) before the constructor’s name. It’s customary to list constructors before other operations in the third compartment.

11 // create GradeBook object 12

13 14 15 16

17 // display initial value of courseName for each GradeBook 18 Console.WriteLine( "gradeBook1 course name is: {0}", 19 gradeBook1.CourseName );

20 Console.WriteLine( "gradeBook2 course name is: {0}", 21 gradeBook2.CourseName );

22 } // end Main

23 } // end class GradeBookTest

gradeBook1 course name is: CS101 Introduction to C# Programming gradeBook2 course name is: CS102 Data Structures in C#

Error-Prevention Tip 4.1

Unless default initialization of your class’s instance variables is acceptable, provide a con- structor to ensure that your class’s instance variables are initialized with meaningful val- ues when each new object of your class is created.

Fig. 4.14 | UML class diagram indicating that classGradeBookhas a constructor with a

nameparameter of typestring.

Fig. 4.13 | GradeBookconstructor used to specify the course name at the time each

GradeBookobject is created. (Part 2 of 2.)

GradeBook gradeBook1 = new GradeBook( // invokes constructor

"CS101 Introduction to C# Programming" );

GradeBook gradeBook2 = new GradeBook( // invokes constructor

"CS102 Data Structures in C#" );

GradeBook

+ ôconstructorằ GradeBook( name : string ) + DisplayMessage( )

+ ôpropertyằ CourseName : string

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

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

(1.020 trang)