logo search
Учебник_ПОА

Encapsulation

A class typically represents the characteristics of a thing, and the actions that it can perform. For example, to represent an animal as a C# class, you might give it a size, speed, and strength represented as numbers, and some functions such as MoveLeft(), MoveRight(), SpeedUp(), Stop() and so on, in which you would write the code to make your "animal" perform those actions. In C#, your animal class would look like this:

public class Animal

{

private int size;

private float speed;

private int strength;

public void MoveLeft() // method

{

// code goes here...

}

// other methods go here...

}

If you browse through the .NET Framework Class Library, you will see that each class represents a "thing," such as an XmlDocument, a String, a Form, and that each thing has various actions that it can perform (methods), characteristics that you can read and perhaps modify (properties) and notifications (events) that it sends out when it performs some given action. The methods, properties and events, along with all the other internal variables and constants (fields), are referred to as the members of the class.

Grouping members together into classes is not only logical, it also enables you to hide data and functions that you do not want other code to have access to. This principle is known as encapsulation. When you browse the .NET Framework class libraries, you are seeing only the public members of those classes. Each class probably also has private members that are used internally by that class or classes related to it, but are not meant to be used by applications. When you create your own classes, you will decide which members should be public, and which should be private.