Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Daniel Solis - Illustrated C# 2010 - 2010.pdf
Скачиваний:
16
Добавлен:
11.06.2015
Размер:
11.23 Mб
Скачать

CHAPTER 4 CLASSES: THE BASICS

Programs and Classes: A Quick Example

A running C# program is a group of interacting type objects, most of which are instances of classes. For example, suppose you have a program simulating a poker game. When it’s running, it might have an instance of a class called Dealer, whose job is to run the game, and several instances of a class called Player, which represent the players of the game.

The Dealer object stores such information as the current state of the card deck and the number of players. Its actions include shuffling the deck and dealing the cards.

The Player class is very different. It stores such information as the player’s name and the amount of money left to bet, and it performs such actions as analyzing the player’s current hand and placing bets. Figure 4-1 illustrates the running program.

Figure 4-1. The objects in a running program

A real program would undoubtedly contain dozens of other classes besides Dealer and Player. These would include classes such as Card and Deck. Each class models some thing that is a component of the poker game.

Note A running program is a set of objects interacting with each other.

51

CHAPTER 4 CLASSES: THE BASICS

Declaring a Class

Although types int, double, and char are defined in the C# language, classes such as Dealer and Player, as you can probably guess, are not defined by the language. If you want to use them in a program, you’ll have to define them yourself. You do this by writing a class declaration.

A class declaration defines the characteristics and members of a new class. It does not create an instance of the class but creates the template from which class instances will be created. The class declaration provides the following:

The class name

The members of the class

The characteristics of the class

The following is an example of the minimum syntax for a class declaration. The curly braces contain the member declarations that make up the class body. Class members can be declared in any order inside the class body. This means it’s perfectly fine for the declaration of a member to refer to another member that is not yet defined until further down in the class declaration.

Keyword

Class name

 

 

class

MyExcellentClass

{

MemberDeclarations

}

For example, the following code shows the outlines of two class declarations:

class Dealer

// Class declaration

{

 

...

 

}

 

class Player

// Class declaration

{

 

...

 

}

 

Note Since a class declaration “defines” a new class, you will often see a class declaration referred to as a class definition both in the literature and in common usage among programmers.

52

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]