Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Microsoft CSharp Programming For The Absolute Beginner (2002) [eng].pdf
Скачиваний:
39
Добавлен:
16.08.2013
Размер:
15.71 Mб
Скачать

concentrate on how to use a custom class inside your programs.

Creating an Instance of the Critter

The Main() method of the CritterName program is almost identical to that of the Critter Menu program, except that I added two lines before the while loop:

static void Main(string[] args) { bool keepGoing = true;

int choice;

Critter myCritter = new Critter(); myCritter.name = "George";

while (keepGoing){

...

} // end while loop

}// end main

Again, I removed some of the code (specifically, the while loop) so that you can concentrate on the part of the program that is new. The complete code is available on the CD−ROM accompanying this book.

The line containing new Critter() creates a new instance of the critter object and assigns it to a variable named myCritter. After you define a class, it is essentially a new variable type, and you can create a variable of that type. The new keyword informs the computer that you will be making an instance of the Critter() class. Critter is the class (or cookie recipe), and myCritter is an instance (a cookie) of that class. In most situations, you work not with the class but with instances of the class. Generally, whenever you create a custom class, you also make an instance (or several instances) of that class. In the next line, you’ll see that you can assign a value to myCritter.name. In fact, when you type myCritter into the IDE, a pop−up menu appears, listing all the possible members of myCritter. You can choose name from this automatic menu in the same way you choose WriteLine or ReadLine from the console object’s automatic menu system.

Referring to the Critter’s Members

I also made a modification to the switch because I wanted the critter to say its name when you talk to it. Take a look at the appropriate section of the switch statement in the Main() method:

case 1:

Console.WriteLine("The critter says: my name is {0}", myCritter.name); break;

This code refers to the name member of the critter object. After you define an object and add members to it, using the object is easy. You don’t have to know exactly how the member is defined or works. You simply refer to it. This is another example of the joys of encapsulation.

Adding a Method

Objects are more interesting when they can do something. As you recall, methods are actions that objects can perform. Now you’ll add a method to the critter so that it can do something interesting. Adding a method to a class is just like adding methods in ordinary programs.

91

Соседние файлы в предмете Программирование на C++