Docstoc

unit1

Document Sample
unit1 Powered By Docstoc
					DATE:MON-20-2011




      BAL
            UMA       E
                  N YA M A I L
                      M80
                          5@G
                               MA
                                                UNIT-1
                                                2010-11             SEM-5                                JNTUK
                                    IL.C
                                           OM




Object-Oriented Concept

                               !! Basic Concept!

     Object-orientation is so called because this
     method sees things that are part of the real
   world as objects. A phone is an object in the
 same way as a bicycle, a human being, or an
  insurance policy are objects. In everyday life,
we simplify objects in our thinking – we work
        with models. Software development does
        essentially the same: objects occurring in
   reality are reduced to a few features that are
    relevant in the current situation. Instead of
real objects, we work with symbols. Properties
    and composition of objects correspond only
 roughly to reality; the model selects only those
       aspects that are useful for carrying out a
   specific task. In figure 3.1, we use model to            DATA ABSTACTION                encaptulation
describe a reality that a teacher owns a bicycle            To define the CIM models and manage them
                            and he reads a book.!               well, understand the concept of Object
                                                          Orientation is an important work since the MOF
                                                           is based on the object-oriented concept. In this
  Figure 3.1 Complex realities are made more
                                                          chapter we will introduce the concept of object-
              manageable by abstract models.!             orientation, class modeling with object-oriented,
                                                                 the critical concept in object-oriented
                                                          programming and finally, we will introduce how
                                                               to use Rational Rose to design the model
OBJECT ORIENTED PROGRAMMING


object oriented programming

Object-oriented programming (OOP)               Some programming language
   is a programming paradigm using         researchers and academics use the
"objects" – data structures consisting first meaning alone or in combination
  of data fields and methods together     with the second as a
   with their interactions – to design distinguishing feature
applications and computer programs.          of object oriented
Programming techniques may include       programming, while
    features such as data abstraction,     other programming
            encapsulation, messaging,         languages which
      modularity, polymorphism, and provide lexical closures
           inheritance. Many modern view encapsulation as encapsulation
programming languages now support              a feature of the
          OOP, at least as an option.            language orthogonal to object Encapsulation means as
       Encapsulation (object-oriented                             orientation. much as shielding. Each
                                                                                     object-oriented object
                        programming)       The second definition is motivated by      has a shield around it.
            From Wikipedia, the free      the fact that in many OOP languages       Objects can't 'see' each
                      encyclopedia                   hiding of components is not          other. They can
                                           automatic or can be overridden; thus           exchange things
                                                                                      though, as if they are
                                              information hiding is defined as a
         In a programming language                                                  interconnected through
                                             separate notion by those who prefer        a hatch. Figure 3.3
  encapsulation is used to refer to one                     the second definition.     shows the concept of
   of two related but distinct notions,                                                the encapsulation. It
                                             As information hiding mechanism
    and sometimes to the combination                                                 separates the external
                               thereof:     Under this definition, encapsulation        aspects of an object
                                          means that the internal representation         from the internal
A language mechanism for restricting                                                implementation details
                                           of an object is generally hidden from
       access to some of the object's                                               of the object, which are
                                          view outside of the object's definition.
                        components.                                                     hidden from other
                                                Typically, only the object's own        objects. The object
 A language construct that facilitates           methods can directly inspect or     encapsulates both data
       the bundling of data with the      manipulate its fields. Some languages             and the logical
methods (or other functions) operating     like Smalltalk and Ruby only allow        procedures required to
                         on that data.                access via object methods,      manipulate the data.!
DATA ABSTRACTION!




Data Abstraction!                    collect essential elements
    Abstraction is the               composing to a compound
presentation of simple               data. These two
concept (or object) to the           abstractions have the same
external                world.       objective: reusable and
Abstraction concept is to            replaceable. Figure 3.2
describe a set of similar            shows an example of data
concrete entities. It focuses        abstraction to abstract
on the essential, inherent           doors as a data structure
aspects of an entity and             with essential properties.
ignoring its accidental
properties. The
abstraction concept is
usually used during
analysis: deciding only
with application-domain
concepts, not making
design                      and
implementation decisions.
    Tw o              popular
abstractions: procedure
a b s t r a c t i o n a n d d at a
abstraction. Procedure
abstraction is to
decompose problem to
many simple sub-works.
Data abstraction is to
MESSAGE PASSING


message passing
                           OBJECT ORIENTED PROGRAMMING CONCEPTS



     Message passing                              model and the process calculi are            level version of a datagram except
                                                  b a s e d o n m e s s a g e p a s s i n g.   that messages can be larger than a
                                                  Implementations of concurrent                packet and can optionally be made
       Message passing in computer
                                                  systems that use message passing can         reliable, durable, secure, and/or
science is a form of communication
                                                  either have message passing as an            transacted.
used in parallel computing, object-
o r i e n t e d p ro g r a m m i n g, a n d       integral part of the language, or as a            !Messages are also commonly
                                                  series of library calls from the             used in the same sense as a means of
interprocess communication. In this
                                                  language. Examples of the former             interprocess communication; the
model, processes or objects can send
                                                  include many distributed object              other common technique being
and receive messages (comprising
                                                  systems. Examples of the latter              streams or pipes, in which data are
zero or more bytes, complex data
structures, or even segments of code)             include Microker nel operating               sent as a sequence of elementary data
                                                  systems pass messages between one            items instead (the higher-level version
to other processes. By waiting for
                                                  kernel and one or more server blocks,        of a virtual circuit).
m e s s a g e s, p ro c e s s e s c a n a l s o
                                                  and the Message Passing Interface
synchronize.
                                                  used in high-performance computing.               Synchronous versus
                                                        !Message passing systems and
      Overview                                    models                                       asynchronous message
                                                        !Distributed object and remote         passing
     !M e s s a g e p a s s i n g i s t h e       method invocation systems like ONC
paradigm of communication where                   RPC, Corba, Java RMI, DCOM,
                                                                                                    !Synchronous message passing
messages are sent from a sender to                SOAP, .NET Remoting, CTOS,
                                                                                               systems require the sender and
one or more recipients. Forms of                  QNX Neutrino RTOS, OpenBinder,
                                                                                               receiver to wait for each other to
messages include (remote) method                  D-Bus and similar are message
                                                                                               transfer the message. That is, the
invocation, signals, and data packets.            passing systems.
                                                                                               sender will not continue until the
When designing a message passing                        !Message passing systems have
                                                                                               receiver has received the message.
system several choices are made:                  been called "shared nothing" systems
                                                                                                    !Synchronous communication
     !W h e t h e r m e s s a g e s a r e         because the message passing
                                                                                               has two advantages. The first
transferred reliably                              abstraction hides underlying state
                                                                                               advantage is that reasoning about the
     !W h e t h e r m e s s a g e s a r e         changes that may be used in the
                                                                                               program can be simplified in that
guaranteed to be delivered in order               implementation of sending messages.
                                                                                               there is a synchronisation point
     !Whether messages are passed                       !Message passing model based
                                                                                               between sender and receiver on
one-to-one, one-to-many                           programming languages typically
                                                                                               message transfer. The second
(multicasting or broadcasting), or                define messaging as the (usually
                                                                                               advantage is that no buffering is
many-to-one (client–server).                      asynchronous) sending (usually by
                                                                                               required. The message can always be
     !Whether communication is                    copy) of a data item to a
                                                                                               stored on the receiving side, because
synchronous or asynchronous.                      communication endpoint (Actor,
                                                                                               the sender will not continue until the
     !P r o m i n e n t t h e o r e t i c a l     process, thread, socket, etc.). Such
                                                                                               receiver is ready.
foundations of concurrent                         messaging is used in Web Services by
computation, such as the Actor                    SOAP. This concept is the higher-
MESSAGE PASSING!


message passing
                                ASYNCHRONOUS MESSAGE PASSING



Asynchronous message passing              from message passing in at least three      depend on exposing the internals of a
systems deliver a message from            crucial areas:                              process.
sender to receiver, without waiting for        • total memory usage                        A subroutine call or method
the receiver to be ready. The                  • transfer time                        invocation will not exit until the
advantage of asynchronous                      • locality                             invoked computation has terminated.
communication is that the sender and           In message passing, each of the        Asynchronous message passing, by
receiver can overlap their                arguments has to have sufficient             contrast, can result in a response
computation because they do not           available extra memory for copying          arriving a significant time after the
wait for each other.                      the existing argument into a portion        request message was sent.
     Synchronous communication            of the new message. This applies                 A message handler will, in
can be built on top of asynchronous       irrespective of the size of the original    general, process messages from more
communication by ensuring that the        arguments – so if one of the                than one sender. This means its state
sender always wait for an                 arguments is (say) an HTML string of        can change for reasons unrelated to
acknowledgement message from the          31,000 octets describing a web page         the behaviour of a single sender or
receiver before continuing.               (similar to the size of this article), it   client process. This is in contrast to
     The buffer required in               has to be copied in its entirety (and       the typical behaviour of an object
asynchronous communication can            perhaps even transmitted) to the            upon which methods are being
cause problems when it is full. A         receiving program (if not a local           invoked: the latter is expected to
decision has to be made whether to        program).                                   remain in the same state between
block the sender or whether to                 By contrast, for the call method,      method invocations. (in other words,
discard future messages. If the sender    only an address of say 4 or 8 bytes         t h e m e s s a g e h a n d l e r b e h ave s
is blocked, it may lead to an             needs to be passed for each argument        analogously to a volatile object).
unexpected deadlock. If messages are      and may even be passed in a general
dropped, then communication is no         purpose register requiring zero
longer reliable.                          additional storage and zero "transfer
     Message passing versus               time". This of course is not possible
                                          for distributed systems since an
calling
                                          (absolute) address – in the callers
     Message passing should be
                                          address space – is nor mally
contrasted with the alternative
                                          meaningless to the remote program
communication method for passing
                                          (however, a relative address might in
information between programs – the
                                          fact be usable if the callee had an
Call. In a traditional Call, arguments
                                          exact copy of, at least some of, the
are passed to the "callee" (the
                                          callers memory in advance). Web
receiver) typically by one or more
                                          browsers and web servers are
general purpose registers or in a
                                          examples of processes that
parameter list containing the
                                          communicate by message passing. A
addresses of each of the arguments.
                                          URL is an example of a way of
This form of communication differs
                                          referencing resources that does
 MESSAGE PASSING IS OBJECT ORIENTED CONCEPT


message passing and locks
                                                               EXAMPLES



Message passing and locks                               Examples of message                            former has no method to handle the
                                                                                                       message, but "knows" another object
     Message passing can be used as a             passing style                                        that may have one. See also Inversion
way of controlling access to resources                                                                 of Control.
                                                       •Actor model implementation
in a concurrent or asynchronous                        •Amorphous computing
system. One of the main alternatives                                                                       Alan Kay has argued that
                                                       •Flow-based programming
is mutual exclusion or locking.                                                                        message passing is more important
                                                       •SOAP (protocol)
Examples of resources include shared                                                                   than objects in OOP, and that objects
memory, a disk file or region thereof,                                                                  themselves are often over-
                                                           Influences on other                         emphasized. The live distributed
a database table or set of rows.
                                                  programming models                                   objects programming model builds
    I n l o c k i n g, a r e s o u rc e i s                                                            upon this observation; it uses the
essentially shared, and processes                                                                      concept of a distributed data flow to
wishing to access it (or a sector of it)                In the terminology of some                     characterize the behavior of a
must first obtain a lock. Once the                 o b j e c t - o r i e n t e d p ro g r a m m i n g   complex distributed system in terms
lock is acquired, other processes are             languages, a message is the single                   of message patterns, using high-level,
blocked out, ensuring that corruption             means to pass control to an object. If               functional-style specifications.
from simultaneous writes does not                 the object "responds" to the message,
occur. The lock is then released.                 it has a method for that message. In
                                                  pure object-oriented programming,
     Wi t h t h e m e s s a g e - p a s s i n g   message passing is perfor med
solution, it is assumed that the                  exclusively through a dynamic
resource is not exposed, and all                  dispatch strategy.
changes to it are made by an
associated process, so that the                       Objects can send messages to
resource is encapsulated. Processes               other objects from within their
wishing to access the resource send a             method bodies.
request message to the handler. If the
resource (or subsection) is available,                 Message passing enables extreme
the handler makes the requested                   late binding in systems. Sending the
change as an atomic event, that is                same message to an object twice will
conflicting requests are not acted on              usually result in the object applying
until the first request has been                   the method twice. Two messages are
completed. If the resource is not                 considered to be the same message
available, the request is generally               type, if the name and the arguments
queued. The sending programme                     of the message are identical. Some
may or may not wait until the request             languages support the forwarding or
has been completed.                               delegation of method invocations
                                                  from one object to another if the
MODULAR PROGRAMMING


Modular programming
                                    OBJECT ORIENTED CONCEPT


Modular programming                          Language support                      The IBM System i also uses
                                                                               Modules in CL, COBOL, and RPG
                                                                               when programming in the Integrated
                                             Languages that formally support
     Modular programming is a                                                  Language Environment (ILE).
                                         the module concept include
software design technique that                                                 Modular programming can be
increases the extent to which software       • Ada
                                                                               perfor med even where the
is composed of separate,                                                       programming language lacks explicit
interchangeable components, called           • BlitzMax
                                                                               syntactic features to support named
modules by breaking down program                                               modules.
functions into modules, each of              • COBOL
which accomplishes one function and                                                 Software tools can create
contains everything necessary to             • Component Pascal
                                                                               modular code units from groups of
accomplish this.                                                               components. Libraries of
                                             • D, Erlang, F, Fortran
                                                                               components built from separately
    Conceptually, modules represent                                            compiled modules can be combined
a separation of concerns, and                • Haskell,
                                                                               into a whole by using a linker.
improve maintainability by enforcing
logical boundaries between                   • IBM/360 Assembler
components.
                                             • IBM RPG, ML
    Modules are typically
incorporated into the program                • Modula-2, Morpho
through interfaces.
                                             • Oberon, OCaml
    A module interface expresses the
elements that are provided and               • Pascal, Perl
required by the module. The
elements defined in the interface are         • PL/1
detectable by other modules.
                                             • Python, and Ruby.
    The implementation contains the
working code that corresponds to the
elements declared in the interface.
MODULAR PROGRAMING


modular programing
                          KEY CONCEPTS,IMPLEMENTATION,HISTORY



Key aspects                                it is claimed, counters the key
                                           assumption of The Mythical Man
     With modular programming,             Month – making it actually possible
concerns are separated such that no        to add more developers to a late
(or few) modules depend upon other         software project – without making it
modules of the system. To have as          later still).
few dependencies as possible is the
goals.                                            Implementation
    When creating a modular
system, instead of creating a                   Message passing has, more
monolithic application (where the          recently, gained ground over the
smallest component is the whole),          earlier, more conventional, "Call"
several smaller modules are built (and     interfaces, becoming the more
usually compiled) separately that,         dominant linkage between separate
when composed together, will               modules as an attempt to solve the
construct the executable application       "versioning problem" (sometimes
program. A just in time compiler may       experienced when using interfaces for
perform some of this construction          communication between the
"on-the-fly" at run time.                   modules).

      This makes modular designed
systems, if built correctly, far more           History
reusable than a traditional monolithic          Tr a d i t i o n a l p r o g r a m m i n g
design, since all (or many) of these       languages have been used to support
modules may then be reused (without        modular programming - since at least
change) in other projects. This also       the 1960s. Modular programming is
facilitates the "breaking down" of         a loosely defined concept with no
projects (through "divide and              official definition. It is, in essence,
conquer") into several smaller             simply a programming technique
projects.                                  [dubious – discuss]. Exactly where
                                           modularized programming ends, and
     Theoretically, a modularized          Dynamically Linked Libraries or
software project will be more easily       Object-oriented programming starts
assembled by large teams, since no         in this context is subjective. It might
team members are creating the whole        be defined as the natural predecessor
system, or even need to know about         of OOP, or an evolutionary step
the system as a whole. They can focus      b eyo n d i t - d e p e n d i n g u p o n
just on the assigned smaller task (this,   viewpoint.
  POLYMORPHISM


                                   POLYMORPHISM |ˌPÄLIˈMÔRˌFIZ+M|
noun
the occurrence of something in several different forms, in particular
• Biology the occurrence of different forms among the members of a population or colony, or in the life cycle of an individual
organism.
• Genetics the presence of genetic variation within a population, upon which natural selection can operate.


  Subtype polymorphism, almost               Another common example is the use        not required, it is understood that the
  universally called just polymorphism       of the "+" operator which allows         different methods will also produce
  in the context of object-oriented          similar or polymorphic treatment of      similar results (for example, returning
  programming, is the ability to create      numbers (addition), strings              values of the same type).
  a variable, a function, or an object       (concatenation), and lists                    Polymorphism is not the same as
  that has more than one form. The           (attachment).                            method overloading or method
  word derives from the Greek                                                         overriding.
  ""!"#$!%&'($)*" meaning "having                This is a lesser used feature of
  multiple forms". This article is an        polymorphism.                                Polymorphism is only concerned
  accessible introduction to the topic,                                               with the application of specific
  which restricts attention to the object-        The primary usage of                implementations to an interface or a
  oriented paradigm. In principle,           polymorphism in industry (object-        more generic base class. Method
  polymorphism can however arise in          oriented programming theory) is the      overloading refers to methods that
  other computing contexts and it            ability of objects belonging to          have the same name but different
  shares important similarities to the       different types to respond to method,    signatures inside the same class.
  concept of degeneracy in biology.          field, or property calls of the same      Method overriding is where a
                                             name, each one according to an           subclass replaces the implementation
       The purpose of polymorphism is        appropriate type-specific behavior.       of one or more of its parent's
  to implement a style of programming                                                 methods. Neither method
  called message-passing in the                   The programmer (and the             overloading nor method overriding
  literature[citation needed], in which      program) does not have to know the       are by themselves implementations of
  objects of various types define a           exact type of the object in advance,     polymorphism.
  common interface of operations for         and so the exact behavior is
  users.                                     determined at run-time (this is called
       In strongly typed languages,          late binding or dynamic binding).
  polymorphism usually means that
  type A somehow derives from type B,             The different objects involved
  or type C implements an interface          only need to present a compatible
  that represents type B. In weakly          interface to the clients' (calling
  typed languages types are implicitly       routines). That is, there must be
  polymorphic.                               public or internal methods, fields,
                                             events, and properties with the same
       Operator overloading of the           name and the same parameter sets in
  numeric operators (+, -, *, and /)         all the superclasses, subclasses and
  allows polymorphic treatment of the        interfaces. In principle, the object
  various numerical types: integer,          types may be unrelated, but since
  unsigned integer, float, decimal, etc.;     they share a common interface, they
  each of which have different ranges,       are often implemented as subclasses
  bit patterns, and representations.         of the same superclass. Though it is
INHERITANCE

inherit |inˈherit|
     verb ( -herited , -heriting ) [ trans. ]
     receive (money, property, or a title) as an heir at the death of the previous holder : she inherited a fortune from her
father.
     • derive (a quality, characteristic, or predisposition) genetically from one's parents or ancestors : she had inherited the
beauty of her grandmother.
     • receive or be left with (a situation, object, etc.) from a predecessor or former owner : spending commitments
inherited from previous administrations.
     • come into possession of (belongings) from someone else : she inherits all her clothes from her older sisters.
     • archaic come into possession of (something) as a right (esp. in biblical translations and allusions) : master, what must
I do to inherit eternal life?


   I nh e r i t a n c e (o bje c t-                relationship                  between                    A superclass allows for a generic
                                                   implementations, whereas subtype                    interface to include specialized
oriented programming)                              p o l y m o r p h i s m i s re l at i o n s h i p   functionality through the use of
                                                   between types (interfaces in OOP).                  virtual functions.
       i n h e r i t a n c e i s a w ay t o        (Compare connotation/denotation.)
compartmentalize and reuse code by                 In some, but not all OOP languages,                      The superclass mechanism is
creating collections of attributes and             the notions coincide because the only               extensively used in object-oriented
behaviors called objects which can be              way to declare a subtype is to define a              programming due to the reusability
based on previously created objects.               new class that inherits the                         that can be achieved: common
In classical inheritance where objects             implementation of another.                          features are encapsulated in modular
are defined by classes, classes can                                                                     objects. Subclasses that wish to
inherit other classes.                                  Inheritance does not entail                    implement special behavior can do so
                                                   behavioral subtyping either. It is                  via virtual methods, without having
       The new classes, known as                   entirely possible to derive a class                 to duplicate (reimplement) the
subclasses (or derived classes), inherit           whose object will behave incorrectly                superclass's behavior.
a t t r i bu t e s a n d b e h av i o r ( i . e.   when used in a context where the
previously coded algorithms) of the                parent class is expected;                                Languages may support both
pre-existing classes, which are                                                                        abstract and concrete superclasses.
referred to as superclasses (or                         Complex inheritance, or
ancestor classes). The inheritance                 inheritance used within an
relationships of classes gives rise to a           insufficiently mature design, may lead
hierarchy.                                         to the yo-yo problem.
       In         prototype-based
programming, objects can be defined
directly from other objects without
                                                            S u b cl a s s e s a n d
the need to define any classes, in                  superclasses
which case this feature is called
differential inheritance.
                                                        A superclass, base class, or parent
    The inheritance concept was                    class is a class from which other
invented in 1967 for Simula.                       classes are derived. The classes that
                                                   are derived from a superclass are
    Inheritance should not be                      known as child classes, derived
confused with (subtype)                            classes, or subclasses.
polymorphism, commonly called just
polymorphism. Inheritance is a
INHERITANCE!                                                                                                    PAGE   11


Inheritance concepts
                     APPLICATIONS                   - OVER RIDING , CODE REUSE



• A subclass is a class that                  •Subclasses and superclasses are            is not to be overridden and behave
                                         often referred to as derived and base            according to the base class.
  inherits some properties
                                         classes, respectively, terms coined by
 from its superclass.                    C++ creator Bjarne Stroustrup, who
                                         found these terms more intuitive than
                                                                                            Code reuse
   • One can usually think of the        the traditional nomenclature.
 subclass as being "a kind of" its                                                          • One of the earliest motivations
 superclass, as in "a square is a kind                                                    for using inheritance was the reuse
 of rectangle":
                                               Applications                               of code which already existed in
                                                                                          another class. This practice is
   • A rectangle has four sides with                                                      usually called implementation
 lengths w and h                                                                          inheritance.
                                             • Inheritance is used to co-relate
                                           two or more classes to each other.
   • A square has all of the               With the use of inheritance we can
 characteristics of a rectangle; in
                                           use the methods and the instance
 addition, w = h                           variables of other classes in any
                                           other classes.
    • In this way, a subclass is a
 more specific version of its
 superclass; While all rectangles            Overriding
 have four sides, the square has the
 more restricted feature that all of
 its sides have the same length.              • Many object-oriented
                                           programming languages permit a
                                           class or object to replace the
   • The subclass-superclass
                                           implementation of an aspect—
 relationship is often confused with
                                           typically a behavior—that it has
 that of classes and instances.
                                           inherited. This process is usually
                                           called overriding.
    • An "instance of cat" refers to
 one particular cat. The Manx cat             • O ve r r i d i n g i n t ro d u c e s a
                                           complication: which version of the
 in the table is still a class — there
                                           behavior does an instance of the
 are many instances of Manx cats.
                                           inherited class use—the one that is
 And if a particular cat (an instance
                                           part of its own class, or the one
 of the cat class) happen to have its
                                           from the parent (base) class? The
 tail bitten off by a fox, that does
                                           answer varies between
 not change the cat class. It's just
                                           programming languages, and some
 that particular cat that has
                                           languages provide the ability to
 changed.
                                           indicate that a particular behavior
 INHERITANCE


inheritance
                                                             LIMITATIONS



In most quarters, class inheritance for                  subtype polymorphism.
the sole purpose of code reuse has
                                                                                                  Limitations and
fallen out of favor.The primary
concern is that implementation
                                                         When someone says
                                                     "polymorphism" in association with
                                                                                              alternatives
inheritance does not provide any                     object orientation what they often            When using inheritance
                                                                                              extensively in designing a program,
assurance of polymorphic                             mean is subtype polymorphism. In
                                                                                              one should note certain constraints
substitutability—an instance of the                  principle, subtype polymorphism
                                                                                              that it imposes.
reusing class cannot necessarily be                  means that an object can be of many
substituted for an instance of the                   types. Like
inherited class. An alternative                                                                    For example, consider a class
                                                                                              Person that contains a person's name,
technique, delegation, requires more                     B objects are not just B objects,
                                                                                              address, phone number, age, gender,
programming effort but avoids the                    they're A objects, too. This is
                                                                                              and race. We can define a subclass of
substitutability issue.                              achieved by inheritance.
                                                                                              Person called Student that contains
      In C++ private inheritance can
be used as form of implementation                        Now you can also do,                 the person's grade point average and
                                                                                              classes taken, and another subclass of
inheritance without substitutability.                    and thanks to subtype
                                                                                              Person called Employee that contains
Whereas public inheritance                           polymorphism C objects are also A
                                                                                              the person's job-title, employer, and
represents an "is-a" relationship and                objects.
                                                                                              salary.
delegation represents a "has-a"
relationship, private (and protected)                     Because both C and B objects
                                                                                                   In defining this inheritance
inheritance can be thought of as an                  are also A objects, they can both be
                                                                                              hierarchy we have already defined
"is implemented in ter ms of"                        assigned to A type variables. This is
                                                                                              certain restrictions, not all of which
relationship.                                        what subtype polymorphism
                                                                                              are desirable:
      Object Oriented-Software                       accomplishes. But this would be
Construction, 2nd edition by                         pointless if the B and C objects were
Bertrand Meyer, the creator of the                   identical. Fortunately they don't have
o b j e c t - o r i e n t e d p ro g r a m m i n g   to be, because thanks to overriding
language Eiffel, lists twelve different              they can be made to behave
uses of inheritance,most of which                    differently.
involve some amount of
implementation inheritance.                               So the principal language
      Inheritance vs subtype                         mechanism behind subtype
polymorphism                                         polymorphism is inheritance (one
      T here are many kinds of                       object can have many types). The role
polymorphisms (in the type system of                 of overriding is to allow subtype
a language). For example,                            objects sharing a common supertype
      templates (generics),                          to behave differently.
      member/operator overloading,
      coercion, and



                  The Collector, 1234 Main Street, Any Town, State ZIP | 123-456-7890 | www.apple.com/iwork
 INHERITANCE


inheritance
                                                   DESIGN CONSTRAINTS



Design constraints
                                                     • Visibility: whenever client
    • Singleness: u s i n g s i n g l e            code has access to an object, it
 inheritance, a subclass can inherit               generally has access to all the
 from only one superclass.                         object's superclass data. Even if the
                                                   superclass has not been declared
   • Continuing the example given                  public, the client can still cast the
 above, Person can be either a                     object to its superclass type.
 Student or an Employee, but not
 both.                                                • For example, there is no way
                                                   to give a function a pointer to a
   • Using multiple inheritance                    Student's grade point average and
 partially solves this problem, as one             transcript without also giving that
 can then define a StudentEmployee                  function access to all of the
 class that inherits from both                     personal data stored in the
 Student and Employee.                             student's Person superclass.

    • However, it can still inherit                  • The Composite reuse principle
 from each superclass only once; this              is an alternative to inheritance.
 scheme does not support cases in                  This technique supports
 which a student has two jobs or                   polymorphism and code reuse by
 attends two institutions.                         separating behaviors from the
                                                   primary class hierarchy and
    • Static: the inheritance                      including specific behavior classes
 hierarchy of an object is fixed at                 as required in any business domain
 instantiation when the object's type              class.
 is selected and does not change
 with time.                                           • This approach avoids the static
                                                   nature of a class hierarchy by
    • For example, the inheritance                 allowing behavior modifications at
 graph does not allow a Student                    run time and allows a single class to
 object to become a Employee                       implement behaviors buffet-style,
 object while retaining the state of               instead of being restricted to the
 its Person superclass. (Although                  behaviors of its ancestor classes.
 similar behavior can be achieved
 with the decorator pattern.) Some
 h ave c r i t i c i ze d i n h e r i t a n c e,
 contending that it locks developers
 into their original design standards.
 INHERITANCE


inheritance
                                                            ROLE



Roles and inheritance                      superclasses; say having a common               some subset of all person objects to
                                           superclass 'LegalEntity' for both               be in an "employee" role. The job
     Sometimes inheritance-based           Person and Company classes for all              information would be associated only
design is used instead of roles. A role,   the common aspects of both. The                 to objects that have the employee
say Student role of a Person describes     distinction between role based design           role. Object-oriented design would
a characteristic associated to the         and inheritance based design can be             also model the "job" as a role, since a
object that is present because the         made based on the stability of the              job can be restricted in time, and
object happens to participate in some      aspect. Role based design should be             therefore is not a stable basis for
relationship with another object (say      used when it's conceivable that the             modelling a class. The corresponding
the person in student role -has            same object participates in different           stable concept is either "WorkPlace"
enrolled- to the classes). Some object-    ro l e s at d i f f e re n t t i m e s, a n d   or just "Work" depending on which
oriented design methods do not             inheritance based design should be              concept is meant. Thus, from object-
distinguish this use of roles from         used when the common aspects of                 oriented design point of view, there
more stable aspects of objects. Thus       multiple classes (not objects!) are             would be a "Person" class and a
there is a tendency to use inheritance     factored as superclasses, and do not            "WorkPlace" class, which are related
to model roles, say you would have a       change with time.                               by a many-to-many associatation
Student role of a Person modelled as             One consequence of separation             "works-in", such that an instance of a
a subclass of a Person.                    of roles and superclasses is that this          Person is in employee role, when he
                                           cleanly separates compile-time and              works-in a job, where a job is a role of
     However, neither the inheritance      run-time aspects of the object system.          his work place in the situation when
hierarchy nor the types of the objects     Inheritance is then clearly a compile-          the employee works in it.
can change with time. Therefore,           time construct. Inheritance does
modelling roles as subclasses can          influence the structure of many                       Note that in this approach, all
cause the roles to be fixed on              objects at run-time, but the different          classes that are produced by this
creation, say a Person cannot then         kinds of structure that can be used             design process form part of the same
easily change his role from Student to     are already fixed at compile-time.               domain, that is, they describe things
Employee when the circumstances                  To model the example of Person            clearly using just one terminology.
change.                                    as an employee with this method, the            This is often not true for other
     From modeling point of view,          modelling ensures that a Person class           approaches.
such restrictions are often not            can only contain operations or data
desirable, because this causes artificial   that are common to every Person                      The difference between roles and
restrictions on future extensibility of    instance regardless of where they are           classes is especially difficult to
the object system, which will make         used. This would prevent use of a Job           understand if one assumes referential
future changes harder to implement,        member in a Person class, because               transparency, because roles are types
because existing design needs to be        every person does not have a job, or            of references and classes are types of
updated. Inheritance is often better       at least it is not known that the Person        the referred-to objects
used with a generalization mindset,        class is only used to model Person
such that common aspects of                instances that have a job. Instead,
instantiable classes are factored to       object-oriented design would consider

				
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
views:10
posted:6/21/2011
language:
pages:14