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

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

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

A goodmodel represents an object in a way which reveals more informationabout the object than was available without the model.Arguably, all programming is based on the principle of abstraction15(all problem decomposition is abstraction by one means or another),but every language lends itself to a particular programming style (theone it makes easiest). Each language provides a different conceptualtoolkit and encourages and enables different design and implementationtechniques. Abstraction, inheritance and polymorphism are the essentialcharacteristics of object-oriented languages.‘Abstraction’, as [Koenig and Moo 1997, p.

9] rather neatly puts it,‘is selective ignorance’. Inheritance and polymorphism are what makeabstraction in object-oriented languages different from abstraction inother programming languages.Inheritance builds on the ‘is-a’ relationship as a way of capturingsimilarities between types.

Objects in a program are defined into a15There is an interesting discussion of abstraction in [Koenig and Moo 1997, p. 75].94INTRODUCTION TO OBJECT ORIENTATIONhierarchy of increasingly specialized types, each of which inherits themore general properties of its parents, while adding specialist propertieswhich can in turn be inherited by child classes that provide furtherspecialization. For example, in a financial application, current accountand savings account specialize the properties and behavior of a genericbank account. A current account ‘is-a’ generic bank account that hasbeen specialized; so is a savings account.Polymorphism (the ability to take multiple forms) enables objects torespond either as specialized types or as the types from which theyinherit, allowing the programmer ‘to ignore the differences betweensimilar objects at some times, and to exploit these differences at othertimes’ [Koenig and Moo 1997, p.

35]. Thus in the financial applicationexample, a current account can be treated either as a current account oras a generic bank account.EncapsulationObject-oriented languages are strongly influenced by the idea of abstractdata types (ADTs). The central idea of an ADT is that it defines a datastructure and the operations which may be performed on it [Bishop 1986,p. 4].16 To use an ADT it is enough to have access to the (public) operationsit supports, without requiring any knowledge of its internal structure, andespecially without requiring any knowledge of its implementation (thatis, the internal data it contains and how it implements the operations itsupports).ADTs are a powerful idea and mark a big step forward in enablingprogrammers to create their own, user-defined, complex types, havingsomething like equal status with the built-in types of a language.

ADTsreally belong to the ‘data abstraction’ revolution (the revolution beforethe object-oriented revolution), which spawned the Modula-2 languageand culminated in the definition of the Ada language.17 Ada broughtADTs into the mainstream, but C++ is the language that has taken Ada’sideas and made them successful.18Support for ADTs, that is encapsulation, does not itself define alanguage as object-oriented (Ada is not object-oriented).

However, it is acentral idea of object-oriented languages. Encapsulation is the most basicpattern an object-oriented system can use. It is also a key programming16For a different view, see [Madsen et al. 1993, p. 278] and [Craig 2000, p. 17].See [Bishop 1986] for a discussion.18For an insight into why, the aside in [Stroustrup 1994, p. 192] about the relative sizesof the Grady Booch component library is illuminating: 125 000 lines of uncommented Adato 10 000 lines of C++.

Ada wasn’t much liked by anyone (see the note in [Kamin andSamuel 1990, p. 248] of Tony Hoare’s Turing Award lecture remarks). ‘What attracted meto C++ had more to do with data abstraction than with object-oriented programming. C++let me define the characteristics of my data structures and then treat these data structures as‘‘black boxes’’ when it came time to use them.’ [Koenig and Moo 1997, p. 12].17THE KEY IDEAS OF OBJECT ORIENTATION95insight, an important step away from a focus solely on algorithm andimplementation. In class-based object-oriented languages, encapsulationof objects is provided automatically by the machinery of class definition.19In the case of C++, encapsulation of user-defined data types through themechanism of class definition is probably the key concept of the language.Classes define objects whose instances are created at run time.

Objectshold values and an object’s methods provide the means of access to itsvalues, whether to set, update, retrieve or perform more complex operations upon them. An object’s methods define the interface that the objectexposes or, in Smalltalk terminology, the protocol that it understands.(Terminology varies between languages: Java has interfaces and methods;Smalltalk has protocols and methods; and C++ has interfaces and whatare interchangeably called either methods or functions.)Object-oriented languages also allow objects to be extended to createnew objects. In class-based, object-oriented languages, inheritance provides the extension mechanism.

(But prototype languages, for example,use a copy-and-modify ‘cloning’ mechanism to create new objects fromold.)In C++, there is no requirement to follow the logical separationof interface from implementation with a physical separation of code. Incontrast, Java formalizes the separation by separating the class declarationfrom the class definition (implementation). The interface provided by aclass for manipulation of instantiated objects of the class is declared inan interface file, with only one class per file.InheritanceInheritance is the mechanism in class-based languages that allows newclasses to be defined from existing ones.

Not all object-oriented languagesare class-based (e.g., there are actor- and prototype-based object-orientedlanguages20 ), but most are. Therefore while, strictly speaking, inheritanceis not universal in object orientation, it is certainly typical.Inheritance is a parent–child relationship between types, usually calledsubclassing in Smalltalk and Java (a class is subclassed from a superclass)and derivation in C++ (a class is derived from a base class).

Whereasan abstract data type is a black box ([Stroustrup 1994, p72]) which can’tbe varied or adapted except by redefining it, inheritance provides amechanism that allows flexible variation of abstract data types, in orderto express both the differences and similarities between general types(such as BigCat ) and their specializations (Lion and Tiger ).19[Beaudouin-Lafon 1994, p. 15] says, ‘a class is simultaneously a type and a module’,where type implies interface and module implies implementation.20Actor languages with an object-oriented flavor include ABCL and Obliq; Self isprobably the best known prototype language and is thoroughly object-oriented [Craig2000].96INTRODUCTION TO OBJECT ORIENTATIONThe key differences in the way that languages approach inheritance arein whether multiple inheritance is supported or not, and in whether theinheritance hierarchy is singly rooted or not.

Smalltalk and Java are singlyrooted, meaning that there is a single privileged root class from whichall other classes ultimately derive and which defines (and implements) auniversal set of common class behavior. In both languages, all classes aresubclasses of an Object class; Eiffel is similar, with all classes derivedfrom the ANY class, either implicitly or explicitly.

In C++, on the otherhand, there is no universal base class: the inheritance hierarchy mayhave multiple roots. C++ also allows multiple inheritance, so that classesare unconstrained in the number of parent classes from which they mayderive. Similarly, Eiffel allows multiple inheritance. Smalltalk allows onlysingle inheritance, that is, a class may only have one parent, while Javaallows multiple inheritance of interfaces, but only single inheritance ofimplementation.Inheritance is not just additive. It does not just consist of adding newdefinitions in child classes; it also enables the redefinition in child classesof the existing behavior of parent classes. Typically this is known asoverriding, the child overriding the behavior of the parent with its ownspecialized behavior.Object-oriented languages typically distinguish between abstractbehavior, which defines an interface to an object but which does notprovide an implementation, and concrete behavior, which both definesand implements an interface.

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

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

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

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