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

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

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

25].Inheritance is used as the mechanism which enables sharing betweenclasses. In other object-oriented languages, classes are definitional constructs that define instances and it is these instances which are objects(i.e., an object instantiates a class but a class is not itself an object). Thisis not the case in Smalltalk, in which everything is an object, includingnumbers, characters, Booleans, arrays, control blocks, and even methodsand classes. Smalltalk has a rich hierarchy of ready-made classes (230classes in Smalltalk-80 with 4500 methods) [Mevel and Gueguen, p. 5].The object purity of Smalltalk extends all the way down to what inother languages would be the purely syntactic level of control structures.This makes its syntax idiosyncratic compared with other languages.Probably the most unfamiliar aspect of Smalltalk syntax for anyone witha background in procedural languages is the absence of familiar controlconstructs such as if – then – else.

Instead, control blocks act asswitches. For example, compare a conventional C-style if – then – elsewith a Smalltalk conditional block, using a Boolean object and ifTrue:and ifFalse: messages. Certainly it can appear radically unfamiliar foranyone coming from a more conventional programming background.A final idiosyncrasy (although it may seem more natural to newer generations of programmers brought up on IDEs rather than the command-line)is that Smalltalk cannot be invoked as a simple language interpreteror compiler, but is instead part of a complete graphical programmingenvironment.

Smalltalk programs do not compile into conventional executables and libraries, with conventional linkage models, but insteaddynamically update the running image of the complete live environment.The Smalltalk system can thus be modified at run time (unlike a conventional compiled executable). The language (and its associated tools)are thus embedded in a live, interactive environment, which is consistentwith the origins of the language and its goals (a teaching language fornovice programmers, based on a ‘physical world’ metaphor). Snapshotsof the environment can be created as persistent images.An irony is that where Smalltalk aims for simplicity, the language(and the associated ‘object theory’) turns out to be surprisingly complex.While Smalltalk failed to gain much hold as a teaching environment, it104INTRODUCTION TO OBJECT ORIENTATIONfound a number of commercial niches (it remains popular for financialmodeling applications) and it has retained its place as an ‘extreme’language for (far from novice) object purists.

A great deal of advancedobject-oriented programming practice and theory, from patterns to thephilosophy of reflection to extreme programming praxis, have originatedin the Smalltalk world.An interesting Smalltalk spin-off is the Self language, designed byRandall Smith and David Ungar, which originated at Xerox as a vehiclefor exploratory programming and an experiment in an object-orientedlanguage not based on classes.

Instead of classes, Self is based on thenotion of prototypes. New objects are derived by cloning and modifyingexisting prototype objects. Self takes the idea of a language embeddedin an environment modifiable at run time to an (interesting) extreme. Byremoving both the theory and the machinery that comes with classes(inheritance, polymorphism and so on), it removes almost all of thecomplexity, while still retaining the power of object-based abstraction.Self espouses as a central principle that an object is completely definedby its behavior.26 The corollary is that programs are not sensitive to theinternal representations chosen by objects or, indeed, any other hiddenproperties of programs.C++C++ originated from a networking-support research project at Bell Labsin 1979, as an attempt by Bjarne Stroustrup to improve C by adding classconcepts derived from Simula to support powerful but type-safe abstractdata type (ADT) facilities. Indeed those origins are made transparent byits first incarnation as ‘C with classes’.The central concept of C++ is that of class [Koenig and Moo 1997].Classes enable user-defined types that encapsulate behavior and data.Originally, C++ classes began as elaborations of C structs.

While structsallow structured data to be defined and managed to create user-definedcomplex data types, classes extend the idea to include method definitionsas well as data. (C++ retains the notion that a simple class that defines nomethods is synonymous with a struct.)In its first implementations, C-with-classes and later C++ were implemented as pre-processors, which translated C++ into plain C and theninvoked the standard C compiler. (Again, the history is in the name: thefirst C++ implementation was named Cpre) [Stroustrup 1994, p. 27]. In ageneral sense, C++ thus includes the C language but C++ is not a pure Csuperset (unlike Objective-C, for example).The goal of C++ is to enable the same level of type safety as is enjoyedby built-in language types to be enjoyed by user-defined data types.

C++26See the Self Programmers Reference Manual, p. 55 at http://research.sun.com/self/language.html.THE LANGUAGES OF OBJECT ORIENTATION105also provides improved type safety for built-in types compared with C, forexample with language constructs designed to support immutable values(the const construction and the ‘reference’ operator). Its secondary goalis to do so without compromising either the efficiency of C or C’s abilityto operate (when necessary) close to the machine level.Compared with Smalltalk, its goals make C++ inherently a hybridlanguage, sacrificing purity in favor of pragmatism. C++ is often said tobe not an object-oriented language at all, but a language which can beused to program in a number of different styles.

The more use that is madeof advanced language features, the closer the style becomes to objectorientation. However, there are advanced features which have little to dowith object orientation (as understood in the purer sense of Smalltalk atany rate), for example the templating support for parametric (also knownas generic) programming styles.In summary, C++ is a strongly statically typed language with supportfor classes.• Objects are optional, but when used they are based on classes, which,at one extreme, may be C-like structs and, at the other, may definepure virtual (polymorphic) objects or may fall somewhere between.• Objects are created from classes by constructor methods and aredeleted by destructor methods, which may be defined (for complexclasses) or default to standard methods if not defined.• Objects can control access to their data and methods by declaringthem private, shared or public.• Values can be made immutable by declaring them const and allobjects can be passed by value, by reference or by pointer.• Separation of interface from implementation is encouraged but notenforced (for example, methods may be declared inline and theirimplementation specified at the point of definition, within a classdefinition).

Definition and implementation can be mixed and thereis no requirement for separate interface definition files. Multipledefinitions and implementation specifications can be provided withina single file. C-style #include preprocessor directives are used tomanage definition inclusion.• There is no notion of a root class and, therefore, no definite classhierarchy.

Multiple hierarchies can be created within a single programand multiple inheritance is allowed (so that a single class may inheritfrom multiple parents). Advanced object-oriented features such asreflection are not supported.Run-time polymorphism is the exception in C++ rather than the ruleand, for all other cases, type checking is performed at compile time.106INTRODUCTION TO OBJECT ORIENTATIONRun-time polymorphism is enabled only for classes which are definedas pure virtual, in which case method dispatch is completed at run timethrough a ‘vtable’ (a virtual method dispatch table).

Virtual methods userun-time binding and are not determined at compile time.C++ retains a conventional C-style execution and linkage model.There is no automatic garbage collection in C++. Memory managementis the responsibility of the programmer, making the language flexible andpowerful but also dangerous (carelessness leads to memory leaks).JavaJust as C++ began as an exercise to improve C, so Java began as anexercise to improve C++ and, in particular, to simplify it, straighten outinconsistencies and make it less dangerous (for example, proof againstmemory leaks) as well as more secure (in the sense of tamper-proof,the origin of the Java ‘sandbox’ application model) and, therefore, moresuitable for a wider range of devices (in particular, for smaller, consumeroriented systems).

Perhaps even more importantly, from the beginningthe Java implementation model aimed at maximum platform neutralityand a write-once–run-anywhere model.Java language programs are thus compiled into an interpreted intermediate language which is executed by a Java virtual machine (VM)running on the target hardware. Any Java code runs on any Java VM, thusproviding abstraction from physical hardware. In other words, Java provides a software environment for code execution rather than a hardwareenvironment.In this sense, Java is like the pure object-oriented model of Smalltalk,which similarly provides a software execution environment based on aVM. Unlike Smalltalk, Java programs are separable from the executionenvironment and its linkage model is more akin to a conventionalexecutable and library-linkage model.The VM approach also allows Java to meet its goals of robustnessand security.

The VM controls access to the resources of the nativeenvironment, thus enabling a garbage-collected execution environment(so that memory management is the responsibility of the environment,not the program), as well as a security sandbox, isolating Java programsfrom the native environment (malicious software can at worst only attackother code executing on the VM and has no access to the VM itself, norto the underlying system).Java programs pay a price for the execution model, in the overheadof interpreting Java intermediate byte code. However, Java VM technology exploiting sophisticated compilation techniques has eroded the rawspeed differences between executing Java byte code on a VM and executing native processor instructions, to the point where execution speeddifferences are almost insignificant.THE LANGUAGES OF OBJECT ORIENTATION107Java has been less successful at reducing latency of program startup,however, which requires the complete Java environment to be initialized.Java has also struggled to slim down its substantial platform memoryfootprint.

For desktop PCs and ‘single-function’ consumer devices suchas set-top boxes, this is less of an issue than it is, for example, on mobilephones, where Java competes for resources with native code. Pure Javasolutions such as JavaOS, which replaces the native operating systemwith a lightweight Java system sufficient only to host the VM, have notbeen successful to date, although the Jazelle project has challenged conventional solutions by providing a Java solution in dedicated hardware.Jazelle remains a contender in the mobile phone space.From a language perspective, Java makes an interesting contrast withC++. It succeeds in its goals of providing an object-oriented language thatis simpler and purer than C++, while avoiding the syntactic eccentricitiesof Smalltalk; it remains syntactically quite conventional and close to itsC++ origins.Like C++, Java is strongly statically typed.

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

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

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

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