The Symbian OS (779886), страница 26

Файл №779886 The Symbian OS (Symbian Books) 26 страницаThe Symbian OS (779886) страница 262018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 26)

Abstract behavior is provided by definingabstract methods (in C++, virtual methods). Abstract methods emphasizethe point that inheritance relationships are defined by methods, but nottheir implementations. Classes can also be defined as abstract. Abstract(pure virtual, in C++) classes cannot have instances. In C++, abstractclasses provide the mechanism for polymorphism. Child classes arerequired to implement the abstract methods of a parent.Inheritance is explicitly a mechanism of class-based languages. Nonclass-based object-oriented languages, for example prototype languages,provide equivalent mechanisms based on the idea of cloning new objectsfrom template objects (‘prototypes’), to create ‘pseudo-classes’ of similarobjects, rather than true classes, but the purpose is essentially the same[Appel 1998, p.

310].PolymorphismIntuitively, the operations that can be performed on a value depend onthe type of the value. Adding numbers makes sense and concatenatingstrings makes sense, but adding strings or concatenating numbers do notmake sense, or not in any generally agreed way.Different programming languages treat the notion of type in differentways. At one extreme, the functional programming world favors completetype-inference systems that amount to full logics (i.e., languages) in theirTHE KEY IDEAS OF OBJECT ORIENTATION97own right and are completely independent of any physical machinerepresentations of values.

At the other extreme, procedural languages suchas C, as well as older languages such as Fortran, have type systems whichhave evolved naturally, and informally, from the physical representationof values in machine memory (bits, bytes, words, long-words, doublewords, and so on).Object-oriented languages fall somewhere between these extremes.Every object in an object-oriented program is really an instance of afully encapsulated, and possibly user-defined, type. In a class-basedlanguage, class definition is the same as type definition.

The inheritancerelationships between objects are type relationships.Polymorphism simply means ‘having many forms’ [Craig 2000, p. 4]. Inan object-oriented context, it is often alternatively described as ‘dynamictyping’. Polymorphism exploits a simple principle of substitutability:two objects related by inheritance (or an equivalent mechanism) sharea common subset of methods. However, the implementation of thosemethods may differ.Methods can be invoked on a child object based simply on what weknow about its parent. We know that a set of methods is supported,whatever their implementation and whether or not we know what otherspecializations have been added. Sometimes we only know the parentclass of an object and not which specialization we are dealing with.

(Forexample, we may know that we have an event, but not what type ofevent we have, or that we are dealing with a document, without knowingwhat kind of document). We therefore know what common methods aresupported by the object, whether or not we know what their behavioris, or what other methods are supported. Often we may not even careabout the details, for example if we simply want to tell an object to printitself.At other times, we may explicitly want to use the specialized behaviorof the derived object.

Polymorphism is the ability of the object to switchbetween these different behaviors, to appear in the run-time context of aprogram variously as an instance of the parent object or as the derivedobject; in other words the ability of an object to behave differently atdifferent points of the program execution.21How polymorphism is implemented varies between languages. Forexample, Smalltalk uses universal run-time type checking to provide theunderlying support for run-time polymorphism. C++, on the other hand,employs static type checking, but allows a ‘virtual’ dispatch mechanismto support constrained run-time polymorphism.2221See [Koenig and Moo 1997, p. 77] for a printing example.Polymorphism is also frequently referred to as ‘dynamic binding’. [Bar-David 1993,p.

87] gives a slightly different slant to his definition of dynamic binding as ‘the ability of anobject to bind – dynamically at run time – a message to an action (or code fragment, if youwill). The idea is that, in a given system, many different objects may respond to the same2298INTRODUCTION TO OBJECT ORIENTATIONA weaker notion of polymorphism is usually qualified as parametricpolymorphism. It refers to functions which can be applied to argumentsof a different type.

This is not polymorphism in the same sense asdynamic typing, because the implication is that such functions executeidentical code [Appel 1992, p. 7] whatever the argument type; in otherwords, overriding of implementation is not allowed. A simple exampleis the language operator (i.e., the built-in function) denoted, in the Clanguage, by &; it creates a pointer to its argument, irrespective of theargument type [Aho et al. 1986, p. 364].

Functional languages suchas ML and Scheme support parametric polymorphism systematically,while conventional procedural languages such as C and Pascal do not(although they may support occasional instances, such as the & operatorin C). Object-oriented languages typically support polymorphism in itsstronger sense.Different languages adopt different strategies for type checking. Theprimary distinction is between static and dynamic type checking. Statictype checking means that types are checked at compile time: if thecompiler encounters static type errors, it rejects the program.

Dynamictype checking occurs at run time, that is, during program execution:if the program encounters dynamic type errors, it halts the program orflags a run-time error in some other way. A different way of stating thedistinction between them is to say that static typing concerns the type ofthe declaration (for example, a C++ reference to a variable or a C pointerto a variable), while dynamic typing concerns the type of the value (forexample, a Smalltalk object) and the difference emphasizes the differentunderlying programming philosophies.Statically typed languages include Pascal, C, C++, Ada and the functional languages ML, Scheme and Haskell. Statically typed languages areregarded as strongly typed if the type system enables static analysis to besufficient to determine that execution of a program will be type correct[Aho et al. 1986, p.

343], although it is not required that the compilernecessarily be able to assign a type to every expression. Such expressionsrequire run-time evaluation. Strongly typed languages include Pascal, C,Ada, Java, Simula, Modula-3 and C++ (except for the single case of adynamically typed method).Dynamically typed languages are those in which all expressions aretyped and checked at run time. For example, Smalltalk and Eiffel use‘dynamic method lookup’ [Appel 1992, p. 7]. (Smalltalk is sometimesdescribed as untyped, like Lisp, but it makes more sense to say that thetype information has been moved where it belongs, into the object aspart of the object’s encapsulation).message – say ‘‘print’’ (i.e., display yourself to a display device); they just respond differently’.

Alternatively, see [Ambler 2004]: ‘Different objects can respond to the same messagein different ways, enabling objects to interact with one another without knowing their exacttype’.THE KEY IDEAS OF OBJECT ORIENTATION99Most languages that perform static analysis (such as Pascal, C, Ada,C++ and Java) require type declarations in programs for all declaredtypes, whether data, operations (i.e. procedures, functions or methods,depending on the language’s terminology) or user-defined types.

(ML andHaskell are exceptions that use static type inference).C++ is something of a hybrid. While it mostly checks types statically,it explicitly enables a mechanism for dynamic typing for polymorphicobjects, as well as a limited form of type analysis (it is really mangledname matching) for objects loaded at run time, such as precompiledlibraries.Dynamic typing in C++ is enabled by addressing an object througha pointer or reference (although not every pointer or reference impliespolymorphism of the object on the other end23 ).

Характеристики

Тип файла
PDF-файл
Размер
2,04 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
Почему делать на заказ в разы дороже, чем купить готовую учебную работу на СтудИзбе? Наши учебные работы продаются каждый год, тогда как большинство заказов выполняются с нуля. Найдите подходящий учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6455
Авторов
на СтудИзбе
305
Средний доход
с одного платного файла
Обучение Подробнее