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

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

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

A C++ pointer addressesan object of the type of the pointer or of a type publicly derived from it.The type is resolved at run time, in principle at each point of execution inthe running program. In C++ (and in Java), this allows the use of a parentclass reference to address a local variable, a class instance variable ora method parameter instantiated by an object of a child class. In thiscase, it is the real type of the object which determines which methodsare called, in cases where methods are overridden in a class hierarchy.24This enables a program to invoke a method on an object with a singlecall that is ‘right first time’, regardless of where in the class hierarchy theobject is defined and regardless of the actual behavior of the method.

(AcalculateBonus() method in a payroll system, for example, performsthe correct calculation, depending on the real type of the object, noton the type of the pointer.) The alternative, if polymorphism were notavailable, would require testing for all possible types of the object toisolate the particular case in every case every time, which is laboriousand error prone, as well as verbose.Java is statically typed but all Java methods are bound at run time.25All Java objects are typed and their types are known at compile time.The compiler performs static type checking.

Dynamic binding means thatpolymorphism is always available, that is, all methods are like virtualmethods in C++ and can be overridden. In other words, every subclasscan override methods in its superclass [Niemeyer 2002, p. 11].Both the static and dynamic approaches have their adherents. Thereally significant difference between them is that each lends itself to acertain style of programming.The most common arguments in favor of statically typed languagesare run-time efficiency (all types are computed at compile time, so23See the discussion in [Lippman 1996, p.

21].See the discussion in [Warren et al. 1999, p. 33–34].25Run time polymorphism, that is, dynamic typing, applies in C++ only through virtualfunctions [Koenig and Moo 1997, p. 35]. A virtual function counts here as a pointer, i.e. apointer to a function in some class, its base class or a class derived from it.24100INTRODUCTION TO OBJECT ORIENTATIONthere is no run-time overhead) and program safety.

Thus, says [Appel1992], programs run faster and errors are caught early. In staticallytyped languages, many programming errors are trivial type errors due toprogrammer oversight, which can be caught and corrected at compiletime. In dynamically typed languages, these may arguably become runtime errors. (Arguably, because adherents of dynamically typed languageswould probably claim that the rigidity and inflexibility of the type systemcaused the errors in the first place.)Type declarations probably do improve code readability and makeprogrammer intentions clearer. On the other hand, dynamically typedlanguages such as Smalltalk and Python allow greater expressivity andexplicitly license a more exploratory programming style, as well asavoiding some of the binary compatibility problems of applications andlibraries written in statically typed languages.4.5 The Languages of Object OrientationSmalltalk remains the canonical object-oriented language, but almostcertainly more object-oriented code has been written in C++ and quitepossibly in Java too.

These three languages constitute the object-orientedmainstream. Python, a newer language more specialized for scriptingand rapid development, may well be on its way to joining them in themainstream; if it can oust Perl from its position as the universal language ofthe Web, it will certainly succeed. C# is another, newer language whichhas set its sights on conquering the Java world as part of Microsoft’s .NETservices effort. However, it currently remains a niche language.The differences between these languages and the other object-orientedlanguages which come and go, are in large part about style (and history).However, in the differences between Smalltalk and C++ in particular,there are insights into more interesting, and deeper, differences about whatmatters most in programming, for example the trade-off between flexibilityand correctness or, perhaps more precisely, what is the best route to correctness and to well-behaved programs which are also capable of evolvingto serve the evolving needs of their users.

Differences of language stylereflect different intuitions about programming style (that is, not just aboutthe style of programs, but also about the different styles of programmingpractice, the actual activity of designing and writing programs).The key language differences can be fairly easily summarized:• single versus multiple inheritance• a single root class versus ad hoc class hierarchies• dynamic versus static type checking and method binding.THE LANGUAGES OF OBJECT ORIENTATION101Some other differences seem to have been relegated to questions ofacademic interest only by the success of the mainstream languages:• encapsulation versus delegation• classes versus prototypes.Languages which seemed to hold promise for a more concrete andintuitive approach to exploratory programming (for example, Self orSqueak, both Smalltalk derivatives) seem to have been rapidly sidelined.One seemingly arcane research topic which has migrated in theother direction, from the fringe to the language mainstream, is reflectionor introspection.

Both Java and C# now support reflection, as doesObjective-C; run-time program objects are reflective (introspective) andare able to consider themselves as data to be manipulated. Smalltalk alsouses reflection, in particular as the mechanism which enables objects toexamine themselves to discover their own types.Java supports reflection for similar reasons, but with a different mechanism, providing a set of reflective classes that allow users to examineobjects to obtain information about their interfaces [Craig 2000, p. 197]and to serialize objects. (In Smalltalk, reflection is a meta-property of allclass objects.)Reflection is a rather esoteric property of a few languages (Smalltalk,Self, Java and C#), but it should be seen as part of the search to definemore flexible languages, with more natural support for distributed andparallel programming, and part of a longer tradition of languages whichinclude meta-level operations enabling a program to represent itself anddescribe its own behavior.

Smalltalk, like Lisp, can manipulate its ownrun-time structures [Craig 2000, p. 184].Other areas of object-oriented research focus less on languagetechniques than on run-time issues, such as just-in-time compilationtechniques (for Java and C#, as well as Python, which are all interpretedlanguages). It seems unlikely that the familiar object-oriented languageswill evolve very radically.

The more likely areas of change will be thedrive towards binary-object encapsulation for distributed programming(in the style of CORBA), which perhaps suggests an eventual convergencebetween object-oriented techniques and more declarative programminglanguage styles, under the influence of the success of XML. (Declarativeprogramming supports greater semantic transparency.)Meanwhile, with C++ and Java, and perhaps Python, as the dominantlanguages, the programming mainstream now seems very squarely objectoriented.SmalltalkSmalltalk dates back to 1972 when the research project from which itoriginates began, although it came of age with the Smalltalk-80 release.102INTRODUCTION TO OBJECT ORIENTATIONIt drew its inspiration from Simula and was developed by Alan Kay’sresearch group at Xerox PARC [Beaudouin-Lafon 1994, p.

57]. In manyways, Smalltalk is the canonical object-oriented language and it wascertainly the first to achieve critical mass. It was launched into thespotlight in 1984, when Byte magazine devoted an entire edition to it.Smalltalk gathered significant commercial momentum. However, sinceits peak in the late 1980s and early 1990s, it has largely been in decline.It has been decisively beaten (in terms of the programming mainstream)by C++ and Java. Its most interesting legacy has been its promise ofa very different way of creating large programs, a more evolutionaryand exploratory approach than is encouraged by the ‘specification first’,top-down style of C++.Smalltalk is a dynamically typed, class-based, message-passing, pureobject-oriented language:• Everything is an object and every object is an instance of a class.• Every class is a subclass of another class.• All object interaction and control is based on exchanges of messages.Conceptually at least, Smalltalk is remarkably clean and uniform,applying the object approach consistently and deeply.

In particular,Smalltalk has a single root class, called Object, from which all objectsultimately inherit. Object itself inherits from the class named Class,which inherits from itself (to satisfy the rule that all classes are subclassesof another class).In Smalltalk, a class whose instances are themselves classes is calleda meta-class. Thus Class is an abstract superclass for all meta-classesand every class is automatically made an instance of its own meta-class.This mechanism is used to introduce the notion of meta-class methods(‘class methods’), which all subclasses inherit and which define thecanonical shared class behavior.

For example, class methods typicallysupport creation and initialization of instances and initialization of classvariables.The Smalltalk system at run time consists only of objects. All interactions between objects take the form of messages. The message interfaceof an object is known as its protocol and message selection determineswhat operations the receiving object should carry out. Each operationis described by a method. There is one method for each selector in theinterface of the class.All objects are run-time instantiations of classes. Classes are definedby class descriptions that specify the class methods (i.e. the meta-classmethods), instance methods and any instance variables [Goldberg andRobson 1989, p. 79].

Method specifications consist of a message pattern(equivalent to a function prototype in C++) which specifies the messageTHE LANGUAGES OF OBJECT ORIENTATION103selector and argument names, and an implementation [Goldberg andRobson 1989, p. 49]. A protocol description for each class lists themessages understood by instances of the class.The message-passing model is uniformly applied as the single controlmechanism for objects. Objects respond to messages and issue messages,and there is no other control mechanism in the system. For example, a newobject is created by sending a message to the required class, which is itselfan object (because Class is itself an object) and can therefore receivemessages. The class object creates the new class instance. Messageexpressions specify a receiver (the intended target object), a selector (themessage name) and any arguments [Goldberg and Robson 1989, p.

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

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

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

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