Студопедия

КАТЕГОРИИ:


Архитектура-(3434)Астрономия-(809)Биология-(7483)Биотехнологии-(1457)Военное дело-(14632)Высокие технологии-(1363)География-(913)Геология-(1438)Государство-(451)Демография-(1065)Дом-(47672)Журналистика и СМИ-(912)Изобретательство-(14524)Иностранные языки-(4268)Информатика-(17799)Искусство-(1338)История-(13644)Компьютеры-(11121)Косметика-(55)Кулинария-(373)Культура-(8427)Лингвистика-(374)Литература-(1642)Маркетинг-(23702)Математика-(16968)Машиностроение-(1700)Медицина-(12668)Менеджмент-(24684)Механика-(15423)Науковедение-(506)Образование-(11852)Охрана труда-(3308)Педагогика-(5571)Полиграфия-(1312)Политика-(7869)Право-(5454)Приборостроение-(1369)Программирование-(2801)Производство-(97182)Промышленность-(8706)Психология-(18388)Религия-(3217)Связь-(10668)Сельское хозяйство-(299)Социология-(6455)Спорт-(42831)Строительство-(4793)Торговля-(5050)Транспорт-(2929)Туризм-(1568)Физика-(3942)Философия-(17015)Финансы-(26596)Химия-(22929)Экология-(12095)Экономика-(9961)Электроника-(8441)Электротехника-(4623)Энергетика-(12629)Юриспруденция-(1492)Ядерная техника-(1748)

Polymorphism




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.

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.


Наследование

Класс может наследовать от другого класса. Это означает, что он наследуемый класс включает все члены — открытые и закрытые — исходного класса. Кроме того наследуемый класс может определять дополнительные члены. Исходный класс называется базовым классом (или классом-предком) а новый класс — производным классом (или классом-наследником) Производный класс создается для специализации возможностей базового класса. Например, можно определить класс Cat, который наследует от Animal. Cat может выполнять все то же, что и Animal, но дополнительно еще урчать. Код C# класса Cat, наследующего от класса Animal, выглядит следующим образом.

public class Cat: Animal { public void Purr() { } }

Нотация Cat: Animal означает, что Cat наследует от Animal и что Cat также имеет метод MoveLeft и три закрытых поля: size, speed и strength. Если определяется класс SiameseCat, который наследует от Cat, он будет содержать все члены Cat, а также все члены Animal.

 

Полиморфизм

В сфере компьютерного программирования полиморфизмом называют возможность производного класса изменять или переопределять методы, которые он наследует от базового класса. Эта возможность используется, если нужно выполнить какие-то особые действия в методе, который отличается от базового, либо не определен в базовом классе,. Например, поскольку метод Animal.MoveLeft должен быть общим, чтобы подходить для всех животных, он является, возможно, очень простым, как например "изменение положения так, чтобы голова животного была в направлении X". Однако для класса Cat этого может быть недостаточно. Может потребоваться указать, как Cat двигает лапами и хвостом при поворотах. Или, к примеру, если описывается класс Fish или класс Bird, то, возможно, потребуется описать в каждом из этих классов свой метод MoveLeft. Поскольку можно настроить поведение метода MoveLeft для конкретного класса, в коде, создающем объект класса Animal и его наследников, отсутствует вызов отдельного метода для каждого животного. Пока объект наследует от Animal, достаточно, чтобы код вызывал метод MoveLeft. При этом будет вызвана та версия метода MoveLeft, которая соответствует конкретному типу животного-объекта в момент обращения к методу.


Constructors

Every class has a constructor: a method that shares the same name as the class. The constructor is called when an object is created based on the class definition. Constructors typically set the initial values of variables defined in the class. This is not necessary if the initial values are to be zero for numeric data types, false for Boolean data types, or null for reference types, as these data types are initialized automatically.

You can define constructors with any number of parameters. Constructors that do not have parameters are called default constructors. The following example defines a class with a default constructor and a constructor that takes a string, and then uses each:

class SampleClass { string greeting;   public SampleClass() { greeting = "Hello, World"; } public SampleClass(string message) { greeting = message; }   public void SayHello() { System.Console.WriteLine(greeting); } } class Program { static void Main(string[] args) { // Use default constructor. SampleClass sampleClass1 = new SampleClass(); sampleClass1.SayHello(); // Use constructor that takes a string parameter. SampleClass sampleClass2 = new SampleClass("Hello, Mars"); sampleClass2.SayHello(); } }




Поделиться с друзьями:


Дата добавления: 2014-12-27; Просмотров: 329; Нарушение авторских прав?; Мы поможем в написании вашей работы!


Нам важно ваше мнение! Был ли полезен опубликованный материал? Да | Нет



studopedia.su - Студопедия (2013 - 2024) год. Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав! Последнее добавление




Генерация страницы за: 0.009 сек.