Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharp_for_Beginners.doc
Скачиваний:
35
Добавлен:
13.02.2015
Размер:
2.39 Mб
Скачать

Инкапсуляция

Обычно класс представляет характеристики объекта и выполняемые им действия. Например, чтобы представить животное как класс C#, необходимо задать ему размер, скорость и силу, представленными в виде чисел, а также некоторые функции, например MoveLeft(), MoveRight(), SpeedUp(), Stop() и так далее, в которых можно написать код для выполнения "животным" этих действий. В C# класс животного может выглядеть следующим образом.

public class Animal

{

private int size;

private float speed;

private int strength;

public void MoveLeft() // method

{

// code goes here...

}

// other methods go here...

}

При просмотре .NET Framework Class Library будет ясно, что каждый класс представляет "объект", например XmlDocument, String, Form, и для каждого такого "объекта" существуют различные действия, который он может выполнить (методы), характеристики, которые можно прочитать и изменить (свойства) и уведомления (события), отправляемые при выполнении некоторых заданных действий. Методы, свойства и события, а также все остальные внутренние переменные и константы (поля) называются членами класса.

Группировка членов в классы имеет не только логический смысл, она также позволяет скрывать данные и функции, которые должны быть недоступны для другого кода. Этот принцип называют инкапсуляцией. При просмотре библиотек классов платформы .NET Framework будут видны только открытые члены этих классов. Возможно, каждый класс имеет закрытые члены, используемые внутренне этим классом или связанными классами, которые не предназначены для использования приложениями. Создавая собственные классы, нужно решить, какие члены будут открытыми, а какие — закрытыми.

Inheritance

A class can inherit another class, which means that it includes all the members, public and private, of the original class, plus the additional members that it defines. The original class is called the base class and the new class is called the derived class. You create a derived class to represent something that is a more specialized kind of the base class. For example, you could define a class Cat that inherits from Animal. A Cat can do everything an Animal can do, plus it can perform one additional unique action. The C# code looks like this:

public class Cat : Animal

{

public void Purr()

{

}

}

The Cat : Animal notation indicates that Cat inherits from Animal and that therefore Cat also has a MoveLeft method and the three private variables size, speed, and strength. If you define a SiameseCat class that inherits from Cat, it will have all the members of Cat plus all the members of Animal.

Polymorphism

In the field of computer programming, polymorphism refers to the ability of a derived class to redefine, or override, methods that it inherits from a base class. You do this when you need to do something specific in a method that is either different or else not defined in the base class. For example, the Animal.MoveLeft method, since it must be very general in order to be valid for all animals, is probably very simple: something like "change orientation so that animal's head is now pointing in direction X". However, in your Cat class, this might not be sufficient. You might need to specify how the Cat moves its paws and tail while it turns. And if you have also defined a Fish class or a Bird class, you will probably need to override the MoveLeft method in different ways for each of those classes also. Because you can customize the behavior of the MoveLeft method for your particular class, the code that creates your class and calls its methods does not have a separate method for each animal in the world. As long as the object inherits from Amimal, the calling code can just call the MoveLeft method and the object's own version of the method will be invoked.

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