Graphics by wanghonghx


									159.331 Programming Languages
         & Algorithms
          Lecture 12 - Object Oriented
               Languages Part 2

159.331             Prog Lang & Alg      1
      Inheritance and Polymorphism
• In imperative languages the declaration of a
  procedure defines the type of each formal
• A Polymorphic procedure comes in more
  than one “flavour” - the type, and possibly the
  number of formal parameters is not fixed, so
  different calls to the same named procedure
  invoke different actual code
• Polymorphism - “many forms”

  159.331             Prog Lang & Alg           2
• Polymorphic procedures and objects are often
  useful when we deal with generic data
  structures which might contain more than one
  sort of object
• eg list of publications
• Each publication object conforms to an interface
  and provides some method doSomething()
• We can invoke doSomething on any object in
  the list even though the actual objects might be
  derived objects and not publication objects
• Publication is the base class, and the objects
  in the list are said to be polymorphic
  159.331            Prog Lang & Alg           3
             Class Hierarchies
• Some languages like Eiffel and Smalltalk and
  Java organise all objects to be part of one big
• In Java every class is derived ultimately from
  the class “Object” which defines methods like
  toString() and other low level systems
• We can therefore have lists etc of type Object
  in Java and the list will be capable of holding
  absolutely any sort of object at all.
  159.331            Prog Lang & Alg           4
               Dynamic Binding
• Static binding happens at compile time
• Dynamic binding happens at run time - it can be used
  to good effect in tandem with polymorphism
• For example code traversing some list of objects might
  invoke doSomething() on each object it finds - but the
  cod e will not know exactly what object it is going to
  find at each location until runtime (it will depend on
  what external input data etc has been read)
• We therefore need to dynamically bind to the particular
  doSomething() code appropriate for the object in
   159.331              Prog Lang & Alg              5
We need to have a switch statement to decide what pub actually is

   159.331                  Prog Lang & Alg                   6
                Virtual Functions
• C++ uses the virtual keyword to specify that we want
  to us e dynamic binding

• So we can say
   class Publication{
     virtual char *Medium(void);
• And just invoke the Medium function letting the run
  time system determine which medium function to
  actually invoke

  159.331                  Prog Lang & Alg          7
• This is neat so why not just make all functions
  virtual and always have dynamic binding?
  – It is expensive (slow) (more so than static binding)
  – A lot of extra linkage code has to be compiled into
    the program to make the dynamic binding work
• We can still do static type checking - we can
  check all the possible cases at compile time
• Note dynamic binding in OO languages is all
  about which actual class of object we are dealing
  with - do not confuse with the scoping done
  with dynamic binding in imperative languages.
   159.331              Prog Lang & Alg              8
              Reference Semantics
• It is ex-licit what is going on in C++ when we set up
  objects or pointers to objects - because pointers are
• Some OO languages hide this idea of reference semantics
• Java for example has no pointers but has a reference type
• In Java we have to say:
   – Thing mything = new Thing();
• mything is of type “reference-to-a-Thing-object”
• The new part allocates memory for a Thing object and
  the assignment makes mything reference it

   159.331                Prog Lang & Alg              9
159.331   Prog Lang & Alg   10
• In C++ we can really only apply the
  polymorphism and dynamic binding ideas to
  objects that are accessed through pointers
• In Java the problem does not arise because we
  do not have pointers - only “object references”
• In modern C++ we now have references as
  well, but we still use pointer apparatus for
  all the OO
• Dynamic allocation in C and C++ is on the
  heap memory - slower than on the stack
  159.331            Prog Lang & Alg            11
Reference semantics often used in OO languages to avoid
the wasted memory situation in case b)

159.331                 Prog Lang & Alg                   12
           Pointers and References
• These are annoyingly close yet separate ideas
• References have a more sophisticated
  semantics and generally have type information
  connected to what they are allowed to
• Although recently typed pointers, including
  void pointers are also possible

 159.331            Prog Lang & Alg          13
            When to Use Inheritance
• Generally when the two entities have an “is-
  a” relationship
• For example, our CalculatorStack is-a Stack
• The inheritance concept therfore works
• Do not confuse with the “has-a” relationship.
• We could implement Calculator Stack as
  having an internal stack of its own …
  159.331            Prog Lang & Alg         14
159.331   Prog Lang & Alg   15
                    is-a or has-a?
• Not always easy to decide - this is the art of OO
  design, choosing what are the important classes to
  maximise reuse and minimise complexity and confusion
• Sometimes obvious - eg defining a car as a
  specialisiation of a tyre is a obvious mistake
   – a car “has four tyres”
• But a car “is-a” vehicle
• Some languages (eg C++ but not Java) support multiple
• Adds to the confusion, and have to use scope resolution
  operator :: to specify which of the multiple possible
  inherited features we refer to. (Name conflict issue)
  159.331                     Prog Lang & Alg        16
                    Discussion on OO
Recall the main aims of OO are to:
• Address problems of flexibility in design process
        • Use data access rather than functions for modularisation
        • Hide internal representation (so we the implementer can change our
          mind later without upsetting rest of the code or our team) - decouples
          the components
        • Dynamic binding helps us localise the code changes (lowering
• Support maximal software reuse
   – Primarily through classes and inheritance
   – BUT will the user use our classes properly? Will they read the
     documentation? How can we ensure our classes are used as
     we intend?

   159.331                        Prog Lang & Alg                          17
            Pre- and post-conditions
• Eiffel supports idea of pre-and post conditions -
  effectively logical assertions about the input data
• eg sqrt function must only be given positive doubles
• Programming by contract is a theoretical apparatus
  supported by Eiffel to set up libraries with appropriate
  logic and rule s about what is allowed.
• There are formal language systems such as the
  language Z that let you reason about pre- and post
  conditions and do “theorem proving” to formally verify
  your cod e is correct for some purpose. Useful when
  life are at stake.
• But surprise, surprise very slow and expensive process
  to apply for most programs.
  159.331               Prog Lang & Alg              18
• C and C++ support a simple idea called assertions -
  the compiler inserts some checking code which will
  cause our program to exit if the assertion fails
   #include <assert.h>
   assert( i < N ); a[i] = i;
• Some language systems are able to analyse (some)
  assertions at compile time
• We can usually conditionally compile these in (or not).
• eg gcc -DNDEBUG myprog.c           leaves out any
  assertion code and therefore executes faster

  159.331                       Prog Lang & Alg       19
            OO Example Languages
• Languages do vary in their degree of support
  for Object orientation
• Ada has some OO features, C++ does too
  although we can still write imperative
  programs in C++ syntax.
• Java requires us to use the OO features to write
  any programs, but ha s many imperative
• Everything in Smalltalk is an object-class!
  159.331            Prog Lang & Alg           20
• An OO language probably needs at least data
  encapsulation, inheritance and dynamic binding to be
  worthy of the name
• Sometimes refer to C++ as a hybrid rather than a
  pure OO language
• The C++ standard itself gets continued attempts to
  clean it up and refine it
• Some proprietary attempts like C# to do the same
• Other languages like Objective-C do some things
  differently again.
• Also languages like Eiffel and Smalltalk that are
  159.331              Prog Lang & Alg              21
Eiffel has fully static type system
without type checking loopholes.

Has 5 so-called expanded classes:
integer, real, double, Boolean
and character

Eiffel supports generics

Operation semantics based on
dynamic binding only, although
The optimizer may revert to
static in unambiguous cases.

Like Java, Eiffel has automatic
garbage collection.
(No delete needed)
     159.331                      Prog Lang & Alg   22
                   OO Summary
• The OO paradigm not only deals with programming, it is
  also a paradigm for designing systems, in particular large
  and complex ones. Object oriented design tries to make
  software systems easier to maintain and change. In
  addition it eases the reuse of existing software.
• The key idea in object-oriented design is to focus on the
  objects in the system, rather than on the system’s
  functions. Objects are less vulnerable than functions to
  changes in the system’s specification.
• The most important concepts in object-orientation are
  objects, classes, inheritance, polymorphism and dynamic

    159.331               Prog Lang & Alg             23
• A class describes a category of objects. It
  contains a description of the internal variables
  of the objects and the operations that can be
  applied to the objects.
• If a new class is defined, it can inherit variables
  and operations from an existing base class.
  Inheritance leads to a hierarchy of classes,
  where each class inherits from its ancestors in
  the hierarchy tree. With multiple inheritance,
  a class can inherit directly from multiple base
  159.331              Prog Lang & Alg            24
• Some languages treat classes as types. They
  apply type-checking rules similar to those for
  subtypes. Since a class can redefine the
  behaviour of an operation inherited from one
  of its ancestors, viewing classes as types may
  not always be appropriate. Other languages
  regard classes as objects.
• The class hierarchy makes it easy to support
  polymorphic procedures, which take the
  parameters of different types. The normal
  static type-checking rules (if any) can be used
  for polymorphic procedures.
 159.331             Prog Lang & Alg           25
• With dynamic binding, if an object executes an
  operation, the run-time class of the object
  determines which code will be executed. With
  static binding, the choice is made at compile time.
  For object-oriented languages, dynamic binding is
  to be preferred: if a class has redefined an
  operation, it is often an error to execute the
  original operation defined in an ancestor class.
• In most OO languages, variables always contain
  pointers to objects. Some languages are less pure,
  and also store scalar data in variables or let the
  programmer decide.
  159.331             Prog Lang & Alg           26
• An important issue in OO
  programming is when to use          •      The OO Programming
  inheritance. Inheritance is usually        paradigm is covered
  appropriate if the “is-a” relation         in Chapter 3 of Bal &
  holds between two classes, but not         Grune, and in Chapter
  if the “has” relation applies.             12 of Sebesta
• Modern thinking is that it is not
  always too good to get carried
  away with the OO idea and to try •         See also Java support
  to make everything an object or to         material on Web site
  over-use inheritance.
• Languages like Java and C++ allow
  you to mix OO and imperative
    159.331                Prog Lang & Alg                  27

To top