Concepts of Object Oriented Programming - PowerPoint PPT Presentation

1 / 143
About This Presentation
Title:

Concepts of Object Oriented Programming

Description:

final static public int spade = 0; final static public int heart = 1; ... default-initargs :suit 'spade :rank 1)) (defmethod flip ((c card)) (setf (faceup? ... – PowerPoint PPT presentation

Number of Views:54
Avg rating:3.0/5.0
Slides: 144
Provided by: Viv130
Category:

less

Transcript and Presenter's Notes

Title: Concepts of Object Oriented Programming


1
Concepts of Object Oriented Programming
  • Based on Timothy Budd
  • Object-Oriented Programming

2
Objects as Abstract Data Types
  • Objects combine state (data fields / instance
    variables/ data members / slots) and behavior
    (operations / methods / function member /
    functions)
  • From the outside clients can only see the
    behavior of objects, from the inside the methods
    provide the behavior through modification of
    state as well as by interacting with other objects

top
pop
top pop push
push
3
Interface and Implementation
  • Parnas Principle 1972 for modules
  • One must provide the intended user with all the
    information needed to use the module correctly
    and nothing more
  • One must provide the implementor with all the
    information needed to complete the module and
    nothing more
  • Parnas Principle for objects
  • A class definition must provide the intended user
    with all the information necessary to manipulate
    an instance of the class correctly and nothing
    more
  • A method must be provided with all the
    information necessary to carry out its given
    responsibilities and nothing more

4
Learning a OO Programming Language (1)
  • Class Definition is like a type definition it
    specifies the data and the behavior (methods) to
    be associated with this data, it does not create
    a value (object) default values for data can be
    specified visibility of data and behavior can be
    specified
  • Object Instantiation is the creation of a new
    instance of a class, i.e. a value (object)
    initial values for the data fields can be passed
    Confusion arises in some strongly typed
    languages where object instantiation takes
    syntactically the form of a declaration
  • Messages have a receiver (the object the message
    is sent to), a message selector (some text
    indicating the message being sent), and arguments

5
Learning a OO Programming Language (2)
  • Class hierarchies are defined when in a class
    definition one or more parent classes can be
    specified (single ltgt multiple inheritance)
  • Inheritance is the property that instances of a
    child class or subclass can access both data and
    behavior (methods) associated with a parent class
    or superclass
  • Method binding or method lookup is a mechanism
    for determining the method to be used in response
    to the message being sent

6
The Card Example
1
  • A card belongs to a suit, has a rank and a color
  • A card can be face up or face down on the table
    (screen) and
  • can be flipped from one position to the other
  • A card can be displayed upon and erased from the
    screen
  • A magic card is a special kind of card, its rank
    can be changed

7
Class Definition
define class ltnamegt ltdata definitionsgt ltmethod
declaration definitionsgt

Card Suit diamond, club, heart, spade Rank
integer FaceUp boolean Color red,
black Flip() ltsome codegt Draw(WwindowX,Yposit
ion) ltsome codegt Erase() ltsome codegt
define class Card ... ...
8
Class Definition visibility, scope, protection

define class ltnamegt ltdata definitionsgt ltmethod
declaration definitions
Card Suit diamond, club, heart,
spade Rank integer
FaceUp boolean NrOfCardsInGame
integer Flip() ltsome codegt
Draw(WwindowX,Yposition) ... Erase()
ltsome codegt Shuffle()
Priv
Priv
Priv
Class
Pub
Pub
Pub
Pub
Class
Pub
9
Issues in class definitions
  • Visibility modifiers to control visibility thus
    manipulation of data fields and methods
  • Getter and setter methods (or accessors and
    mutators) to control how data is accessed and
    modified
  • Constant or immutable data fields to guarantee no
    changes will occur
  • Class data fields that are shared in common
    amongst all instances
  • Order of methods in a class declaration
  • Separating definition and implementation
  • Interfaces
  • Nested classes versus inner classes

10
Classes and Methods in C (1)
  • C distinguishes interface files (.h extension)
    and implementation files
  • The (conditional) include preprocessor directive
    can be used to "import" interface descriptions in
    implementation files
  • Class descriptions are much like structure
    definitions but both data members (data values)
    and function members (methods) are allowed
  • Since methods are treated simply as special types
    of fields, a method and a data field can not
    share a common name
  • Methods with the same name as the class are
    special they are constructors used when creating
    instances of the class

11
Classes and Methods in C (2)
  • The keyword private precedes those portions of
    the code that can be accessed only by the methods
    of the class itself
  • The keyword public precedes those portions of the
    code that can be accessed by clients of the class
  • Since users of the class are mainly interested in
    the public parts, these should come first
  • Descriptions of private members are given for
    the benefit of the compiler only, the clients of
    the class should not see them -gt violation of
    Parnas' first principle

12
Classes and Methods in C (3)
  • An implementation file for a class must provide
    definitions for the methods described in the
    interface file (unless it is a pure virtual
    method)
  • Inline functions are provided to encourage
    programmers to use the principles of abstraction
    and encapsulation while at the same time avoiding
    the overhead of procedure call
  • Inline definitions also occur when the body of a
    method is defined directly in the class
    definition it makes class definitions harder to
    read and some compilers require the private data
    members to be listed before the public interface

13
C Card Interface File
  • class card
  • public enum suits diamond, club, heart,
    spade
  • enum colors red, black
  • card(suits,int) //constructor
  • colors color() //access attributes
  • bool faceUp?()
  • int rank()
  • suits suit()
  • void flip() //actions
  • void draw(window , int, int)
  • void erase(window , int, int)
  • private bool faceUp
  • int rankValue
  • suits suitValue

14
C Card Implementation File
  • include "card.h"
  • card card(suits sv ,int rv)
  • suitValue sv
  • rankValue rv
  • faceUp true
  • inline int cardrank()
  • return rankValue
  • colors cardcolor()
  • if (suit()heart suit()diamond)
  • return red
  • else return black
  • void cardflip()
  • faceUp ! faceUp

15
C Card Interface File bis
  • class card
  • private bool faceUp
  • const int rankValue
  • const suits suitValue
  • public enum suits diamond, club, heart,
    spade
  • enum colors red, black
  • card(suits sv , int rv) suitValue(sv),
    rankValue (rv) //constructor
  • colors color() //access attributes
  • bool faceUp?() return faceUp
  • int rank() return rankValue
  • suits suit() return suitValue
  • ...

16
Java
  • Java is NOT a dialect of C, there are
    superficial surface similarities but the
    underlying differences are substancial.
  • Java does not have pointer, reference, structure,
    and union types, goto statement, function
    definition or operator overloading
  • Java uses garbage collection for memory
    management, introduces the concept of interfaces,
    introduces packages and package visibility,
    supports multithreading and exception handling
  • Java is a very portable language due tot he use
    of a virtual machine

17
Classes and Methods in Java
  • There is no preprocessor, global variables or
    enumerated data types. Symbolic values are
    created by declaring and initialising a data
    field with the keywords final and static
  • The keyword static used on data fields indicates
    that only one copy of the data field exists which
    is shared by all instances. The keyword static on
    a method indicates that this method exists even
    when no instance of the class exist. A Java
    program needs one class with a main static
    method.
  • Method implementations must be provided directly
    in the class definition
  • The public and private keywords are applied
    individually to every instance variable and
    method definition

JAVA 1.5 !
18
Java Card Class (1)
  • class Card
  • final static public int red 0 // static
    values
  • final static public int black 1
  • final static public int spade 0
  • final static public int heart 1
  • final static public int diamond 2
  • final static public int club 3
  • private boolean faceUp // data fields
  • private int rankValue
  • private int suitValue

19
Java Card Class (2)
  • Card (int sv, int rv) // constructor
  • suitValue sv rankValue rv faceUp
    true
  • public boolean faceUp?() return faceUp
    // access attributes
  • public int rank() return rankValue
  • public int suit() return suitValue
  • public int color() if (suit() heart
    suit() diamond) //actions
  • return red
  • return black
  • public void flip() faceUp ! faceUp
  • public void draw( Graphics g, intx, int y)
  • //class Card

20
CLOS
  • Common Lisp Object System is an object oriented
    extension of the LISP language (Scheme is a LISP
    dialect)
  • CLOS uses the generic function approach as
    opposed to message passing to invoke
    class-specific operations
  • CLOS supports automatic updating of instances
    when class definitions are altered and allows
    instances to become instances of a different
    class again supporting appropriate updating for
    the instances

21
CLOS Generic Functions
  • Assume that types or classes rational and complex
    exist and following definitions
  • (defgeneric plus (x y))
  • (defmethod plus (x y) ( x y))
  • (defmethod plus ((x rational) (y rational))
    (ltsome bodygt))
  • (defmethod plus ((x complex) (y complex)) (ltsome
    bodygt))
  • The method executed when calling (plus A B) will
    depend on the types of A and B, the method is
    chosen by a process that selects, sorts and
    combines the applicable methods

22
Classes and Methods in CLOS
  • The defclass macro defines a named class and
    returns the new class object
  • A CLOS class defines the slots contained in the
    instances of that class
  • A slot has a name and can contain a single value
    a slot without a value is an unbound slot
  • Both slot-specifiers and class-options are used
    to determine the characteristics of the slots and
    to create ways to manipulate the slot
  • Documentation can be added to both slots and the
    class object a a whole

23
Classes and Methods in CLOS
  • The allocation slot-specifier allows to
    distinguish between local and shared slots. A
    slot is local when its value is unique to an
    individual instance. A slot is shared when its
    value is common to all instances of that class
  • The type slot-specifier allows to specify a type
    for the slot
  • The documentation slot-specifier allows to add
    some documentation to a slot

24
Classes and Methods in CLOS
  • The reader, writer and accessor
    slot-specifiers create special methods that allow
    reading, writing or both of values for that slot
  • The initarg slot-specifier introduces a keyword
    that can be used while instantiating a class to
    initialise a slot
  • The initform slot-specifier allows to specify a
    default value for a slot
  • The documentation class-option allows to add
    some documentation to a class
  • The default-args class-option allows to specify
    default values for slots of the class using the
    initarg keywords

25
Classes and Methods in CLOS
  • The defmethod macro defines a method and returns
    a method object
  • The class the method is defined on is explicitly
    mentioned in the lambda list as a specialised
    parameter
  • Methods can be qualified as before, after or
    around
  • When no generic function with the same name
    exists yet it is automatically created with a
    compatible lambda list
  • When a generic function with the same name exists
  • the lambda list must be compatible otherwise an
    error is signalled
  • when it does not contain a method object with the
    same parameter specialisers and qualifiers a new
    method object is added
  • when it does contain a method object with the
    same parameter specialisers and qualifiers the
    old method object is replaced

26
CLOS Class Card (1)
  • (defclass card ()
  • ((faceup initarg faceup accessor faceup?
    allocation instance initform 'true)
  • (suit initarg suit reader suit
  • allocation instance)
  • (rank initarg rank reader rank
  • allocation instance)
  • (owner allocation class reader owner
  • initform 'vivi))
  • (documentation "an example class"))

27
CLOS Class Card (2)
  • (defclass card ()
  • ((faceup initarg faceup accessor faceup?
    allocation instance initform 'true)
  • (suit initarg suit reader suit
  • allocation instance)
  • (rank initarg rank reader rank
  • allocation instance))
  • (default-initargs suit 'spade rank 1))
  • (defmethod flip ((c card))
  • (setf (faceup? c) (not (faceup? c))))
  • (defmethod color ((c card))
  • (if (or (eq (suit c) 'heart) (eq (suit c)
    'diamond))
  • 'red 'black))

28
Instantiation and initialisation

make-instance ltclassgt ltinitial valuesgt
(a Card) Suit diamond Rank 9 FaceUp
false Color red
make instance Card diamond, 9, false
make instance Card spade, 4, true
(a Card) Suit spade Rank 4 FaceUp
true Color black
29
Messages Passing
send message ltobjectgt ltmessage selectorgt lt
argumentsgt

(a Card) Suit diamond Rank 9 FaceUp false
Flip()
true
Shuffle()
Card
30
Issues in Creation and Initialisation
  • Stack versus Heap allocation - Automatic versus
    Dynamic variables - Implicit versus Explicit
    creation
  • Manual Memory Recovery Memory leaks - Dangling
    Pointers versus Automatic Garbage collection
    expensive
  • Explicit versus Implicit Pointers
  • Immutable Creation or Single Assignment instance
    variables or slots
  • Initialisation and defaults Constructors
  • Memory Recovery Destructors

31
Issues in Message passing
  • Message passing is the dynamic process of asking
    an object to perform an action
  • Messages have a receiver (the object the message
    is sent to), a message selector (some text
    indicating the message being sent), and arguments
  • Accessing the receiver from within a method
  • Method lookup is a mechanism for determining the
    method to be used in response to the message
    being sent
  • The difference between statically and dynamically
    typed languages is important with regard to
    message passing

32
Creation and Initialisation in C
  • Both automatic and dynamic variables exist
  • An automatic variable is assigned space when the
    block containing its declaration is entered the
    declaration need not to be in the beginning of
    the block. The instance that becomes the value of
    the variable is implicitly created and the space
    is allocated on the stack. Space is freed when
    control exits from the block.
  • A dynamic variable implies the use of an explicit
    pointer and explicit instance creation through
    the new operator. Space is allocated on the heap
    and must be freed explicitly through the delete
    operator

33
Creation and Initialisation in C
  • Initialisation in C is facilitated through the
    use of constructors these are methods that are
    invoked implicitly each time an object of the
    class is created either implicitly or explicitly
  • The operator overloading mechanisms of C
    supports the use of multiple constructors on one
    class to allow for multiple initialisation styles
  • There is syntactical support for the use of
    constructors in the declaration of automatic
    variables and in the new operator
  • Constructors can pass arguments to constructors
    of encapsulated objects

34
Creation and Initialisation in C
  • When the body of a constructor is a set of simple
    assignments to instance variables it can be
    replaced by initialiser clauses in the function
    heading
  • Values can be declared as immutable through the
    use of the const keyword instance variables that
    are declared as constant must be initialised with
    an initialisation clause because they can not be
    the target of an assignment statement
  • Memory clean up in C is facilitated through the
    use of destructors these are methods that are
    invoked implicitly each time an object of the
    class is deleted either implicitly or explicitly

35
Message Passing in C
  • A method in C is named a member function
    passing a message to an object is referred to as
    invoking a member function
  • Syntax is similar to accessing data members with
    arguments in parenthesized list use parentheses
    even if no arguments
  • The pseudo-variable this is associated with a
    pointer to the receiver of a message it can be
    used to send subsequent messages to the receiver
    or to pass the receiver as an argument to a
    subsequent message

36
C Card Example
  • card thecard(hearts, 9)
  • card mycard
  • mycard new card(hearts, 9)
  • thecard.draw(win1,10,10)
  • if(thecard.faceUp?())
  • mycard-gtdraw(win1,10,10)
  • if(mycard-gtfaceUp?())
  • colors cardcolor()
  • if (this-gtsuit()heart this-gtsuit()diamond
    )
  • return red
  • else return black
  • void carddosomething (int i)
  • dootherthing(this,i)

37
Creation and Initialisation in Java
  • Java uses automatic garbage collection, the
    programmer does not have to deal with memory
    management
  • All variables of some object type are initially
    assigned the value null
  • Object values are created with the operator new
    space is allocated on the heap, the pointers are
    always implicit
  • The syntax of the new operator requires the use
    of parentheses even if arguments are not
    necessary
  • Constructors in Java do not support initialiser
    clauses
  • Constructors in Java can call other constructors
    on the same class by using the keyword this it
    allows to factor out common behavior

38
Creation and Initialisation in Java
  • The destructor in Java is represented by a
    finalize function. This function is invoked
    whenever the memory has been recovered through
    garbage collection thus never rely on it and use
    for optimisation only
  • The new operator in Java can take a string as
    argument. This allows to determine at run-time
    the type of the object to be allocated since the
    string can be built up through an expression
  • Instance variables that cannot be reassigned can
    be created through the keyword final

39
Message Passing in Java
  • The only notable difference with C lies in the
    fact that variables declared as class types have
    objects as values (the pointer is implicit) this
    is also the case for the pseudo-variable this
  • card mycard new card(hearts, 9)
  • mycard.draw(win1,10,10)
  • if(mycard.faceUp?())
  • colors cardcolor()
  • if (this.suit()heart this.suit()diamond)
  • return red
  • else return black

40
Creation and Initialisation in CLOS
  • CLOS uses automatic garbage collection, the
    programmer does not have to deal with memory
    management
  • The generic function make-instance is used to
    create and initialise new instances of a class
  • The first argument to make-instance is a class
    object or a class name, the rest of the arguments
    form the initialisation argument list
  • The initialisation arguments that are supplied
    are combined with the default initialisations
    for the slots that are not
  • Storage for the instance is allocated on the
    heap, the slots are filled with the values and an
    anonymous instance object is returned

41
Creation and Initialisation in CLOS
  • Initialisation is CLOS is very sophisticated
  • The same initarg name can occur in multiple slots
  • One slot can have multiple initarg names
  • Two initarg names that are synonymous can occur
    in the lambda list of an initialisation method
  • Methods can be written to control initialisation
    explicitly
  • Initargs can be used to supply arguments to
    methods
  • .
  • Initialisation in CLOS occurs not only when
    making a new instance but also
  • When reinitialising an instance
  • When updating an instance when its class is
    updated
  • When updating an instance to change its class to
    another class

42
Message Passing in CLOS
  • Methods are defined relative to a specific class.
    For each set of methods with a given name there
    is a generic function. Which method will be
    called upon calling a generic function will
    depend on the class arguments passed to the
    generic function
  • Syntactically a message send is a function call,
    the receiver of the message is the first argument
    of the function call and can be used naturally
    to send subsequent messages to the receiver or to
    pass the receiver as an argument to a subsequent
    message

43
CLOS Card Example (1)
  • ? (setf test (make-instance 'card suit 'spade
    rank 9))
  • ltCARD x22F0A0Egt
  • ? (rank test)
  • 9
  • ? (suit test)
  • SPADE
  • ? (owner test)
  • VIVI
  • ?(faceup? test)
  • T
  • ?(setf (rank test) 10)
  • gt Error Undefined function SETFCOMMON-LISP-USE
    RRANK called with arguments (10 ltCARD
    x550B06Egt) .

44
CLOS Card Example (2)
  • ?(slot-value test 'rank)
  • 9
  • ? (setf (slot-value test 'rank) 10)
  • 10
  • ? (rank test)
  • 10
  • ? (faceup? test)
  • T
  • ? (flip test)
  • NIL
  • ? (faceup? test)
  • NIL
  • ? (color test)
  • BLACK

45
CLOS Card Example (3)
  • ? (setf other (make-instance 'card suit 'spade
    rank 2 faceup 'false))
  • ltCARD x22F289Egt
  • ? (rank other)
  • 2
  • ? (faceup? other)
  • FALSE
  • ? (owner other)
  • VIVI

46
Class Hierarchy
Card Suit diamond, club, heart, spade Rank
integer Flip() ltsome codegt

define class ltnamegt ltsuperclassesgt ltdata
definitionsgt ltmethod definition declarationsgt
define class Magic Card Card ... ...
Magic Card Change-Rank(R integer) ltsome codegt
47
Inheritance
  • Inheritance is the property that instances of a
    child class or subclass can access both data and
    behavior (methods) associated with a parent class
    or superclass
  • Inheritance has an extension flavor the behavior
    and data associated with the child class is a
    larger set that the behavior and data associated
    with the parent class
  • Inheritance has a contraction flavor the child
    class is a more specialized or restricted form of
    the parent class
  • Inheritance is transitive
  • Subclasses can override behavior of superclasses

48
Inheritance Message Lookup

(a Magic Card) Suit diamond Rank 9 FaceUp
false
Change-rank(1)
1
(a Card) Suit diamond Rank 9 FaceUp false
Change-rank(1)
49
Subclass, Subtype and Substitutability
  • Subclassing and subtyping is not exactly the
    same thing
  • The substitutability principle says that given
    two classes A and B, where B is a subclass of A,
    it should be possible to substitute any instance
    of class B for instances of class A in any
    situation with no observable effect
  • The term subtyping is often used to refer to a
    subclass relation in which the principle of
    substitutability is maintained, to distinguish it
    from a more general subclass relationship that
    does not necessarily satisfy this principle
  • Statically typed languages place much more
    emphasis on the principle of substitutability
    than do dynamically typed languages

50
Forms of Inheritance
  • Inheritance is used in a surprisingly variety of
    ways. Some general abstract categories are
  • Subclassing for specialisation
  • Subclassing for specification
  • Subclassing for construction
  • Subclassing for generalisation
  • Subclassing for extension
  • Subclassing for limitation
  • Subclassing for variance
  • Subclassing for combination

51
Subclassing for Specialisation (subtyping)
  • The child class is a specialised form of the
    parent class but satisfies the specifications of
    the parent class completely
  • The principle of substituta-bility is explicitly
    upheld
  • Is an ideal form of inheritance, good designs
    should strive for it

Window Move Resize
TextWindow Edit
52
Subclassing for Specification
Abstract
  • The child class implements behavior described but
    not implemented in the parent
  • Is a special case of sub-classing for
    specialisation
  • The parent class is an abstract class it is not
    permitted to create instances of it
  • Is used to guarantee that classes maintain a
    common interface, i.e. implement the same methods

Graphical Object Move //no impl Draw //no impl
Ball Move Draw
Card Move Draw
53
Subclassing for Construction
  • The child class gets most of its desired
    functionality from the parent class only changing
    names of methods or modifying arguments
  • Breaks the principle of substitutability
    intentionally
  • Opens a fast and easy route to new data
    abstractions

List Cons
Set Insert
Stack Push
54
Subclassing for Generalisation
  • The child class modifies or extends the parent
    class to obtain a more general kind of object
  • Used when building upon a base of existing
    classes that are difficult to modify
  • Indicates an emphasis on data rather than
    behavior in the design of the class hierarchy
  • Should be avoided in favor of inverting the class
    hierarchy and using subclassing for specialisation

Window Display
Colored-Window Color Display //override
55
Subclassing for Extension
  • Adds totally new abilities to the subclass new
    methods are added to those of the parent with a
    functionality that is not strongly tied with the
    existing methods
  • As the functionality of the parent class remains
    untouched it obeys the principle of
    substitutability

Set Insert Is-element-of?
String-Set Search-Prefix
56
Subclassing for Limitation
  • The subclass modifies or overrides methods of the
    parent class to eliminate functionality leaving a
    a subclass with smaller or more restrictive
    behavior
  • In an explicit contravention of the principle of
    substitutability
  • Also used when an existing base of classes is
    hard to modify

Deque PushFront PushBack
Stack PushBack //error
57
Subclassing for Variance
  • Is employed when two classes have similar
    implementations but no conceptual hierarchical
    relation
  • One of the two classes is arbitrarily selected to
    be parent the common code in inherited, the
    specific code is overridden
  • Usually a better alternative is to factor out the
    common code and have the two classes inherit from
    a common superclass

Mouse Mark-Position Select
GraphicsTablet Mark-Position
58
Subclassing for Combination
  • Used to give the subclass a combination of
    features from two or more parent classes
  • Also known as multiple inheritance
  • Becomes a problem when clashes occur, so subtle
    and complex that a complete discussion follows

Student AccessPriv GetGrade
Teacher AccessPriv GiveGrade
Teaching-Assistant
59
Inheritance in C (1)
  • Inheritance is indicated in the class header by
    enumerating the parent classes multiple
    inheritance is supported
  • The keywords public and private in the class
    header modulate visibility of inherited members
    private is used for inheritance for construction
  • class TablePile public CardPile ...
  • class Set private List ...
  • Constructors of child classes can explicitly
    invoke the constructor of the parent class with
    an initialisation clause
  • TablePile TablePile(int x, int y, int c)
  • CardPile (x, y) //initialise parent
  • ... //initialise child

60
Inheritance in C (2)
  • Protected is an extra keyword that can be used
    with classes formed by inheritance. Protected
    members in a class definition are accessible in
    subclasses but not in client classes
  • The keyword virtual indicates that a member
    function is likely to be overridden by a subclass
    or is in fact overriding a method from the
    superclass (the keyword is optional in the
    subclass)
  • The semantics of overriding in C are subtle but
    important much depends on how the receiver has
    been declared and on the use of the keyword
    virtual. The discussion follows.

61
Inheritance in Java (1)
  • Subclasses are declared using the keyword extends
  • class TablePile extends CardPile ...
  • All classes are derived from a single root class
    Object if no superclass is mentioned, Object is
    assumed
  • class CardPile extends Object ...
  • class CardPile ...
  • Interfaces are a new concept in Java, they define
    a protocol but no implementation
  • public interface Storing
  • void WriteFrom (Stream s)
  • void ReadFrom (Stream s)

62
Inheritance in Java (2)
  • A class can indicate that it implements an
    interface instances of such a class can be
    values of a variables declared as the interface
    type
  • public class BitImage implements Storing
  • void WriteOut (Stream s) ...
  • void ReadOut(Stream s) ...
  • Only single inheritance is supported but a class
    can implement many interfaces interfaces on the
    other hand can extend multiple interfaces
  • The keyword protected has the same meaning as in
    C

63
Inheritance in Java (3)
  • The idea of subclassing for specification is
    supported in Java with the modifier abstract. It
    is not permitted to create instances of an
    abstract class, only subclasses. Defining a class
    abstract ensured that it will be used only as a
    specification, not an implementation.
  • A method also can be declared to be abstract and
    if so it does not need an implementation it must
    be overridden in subclasses
  • The modifier final used with a class indicates
    that the class cannot be subclassed the modifier
    final used with a method indicates that the
    method can not be modified by a refinement

64
Inheritance in Java (4)
  • The constructor of a child class will always
    invoke the constructor for the parent class this
    invocation always takes place before the code of
    the constructor is executed
  • If the constructor for the parent class needs
    arguments, the pseudovariable super is used as if
    it were a function if no call on super is made
    explicitly, the default constructor (the one with
    no arguments) is used
  • Class DeckPile extends CardPile
  • DeckPile (int x, int y, int c)
  • super(x,y) //initialise parent
  • ... //initialise child

65
Inheritance in CLOS
  • Inheritance is indicated in the defclass macro by
    enumerating the parent classes after the class
    name multiple inheritance is supported
  • (defclass TablePile (CardPile) ...)
  • Both shared and local slots are inherited and can
    be shadowed all slots specifiers are inherited
    and combined
  • Class options including default initialisation
    arguments are inherited and combined
  • A Class Precedence List is computed to control
    combination
  • Methods are inherited too

66
Benefits of Inheritance
  • Software Reusability Code sharing when
    behavior is inherited from another class the code
    does not have to be rewritten this saves time,
    reduces size and increases reliability
  • Consistency of Interface when many classes
    inherit from the same superclass it is easier to
    guarantee that interfaces to similar objects are
    indeed similar
  • Components
  • Rapid prototyping
  • Frameworks

67
Cost of Inheritance
  • Execution Speed inherited methods, which must
    deal with arbitrary subclasses, can be slower
    than specialised code
  • Program Size the use of software components from
    a library imposes a size penalty over code
    written for a specific project
  • Message Passing Overhead message passing is more
    costly than simple procedure call
  • Program Complexity overuse of inheritance may
    obscure the control flow of a program, cfr. the
    yo-yo problem

68
Mechanisms for Software Reuse
  • The two most common mechanisms for software reuse
    are composition and inheritance
  • The "has-as" relationship between two concepts
    holds when the one is a component of the other
    but the two are not in any sense the same thing
  • The "is-a" relationship between two concepts
    holds when the one is a specialised instance of
    the other
  • Common sense helps most of the time
  • a car has an engine a dog is a mammal
  • a car is an engine a dog has a mammal
  • an engine is a car a mammal has a dog

69
Composition and Inheritance the gray area
List Cons Car Length Member
List Cons Car Length Member
Set Elements List Add Size Member
Set Add Size
70
Composition
  • To reuse an existing data abstraction a portion
    of the state of the new data type is to be an
    instance of the existing structure
  • Operations on the new data type are implemented
    using the operations of the existing data type
  • There are absolutely no claims on
    substitutability the two data types are entirely
    distinct
  • Composition can exist in both object oriented and
    non-object oriented languages the only
    significant difference between languages is in
    how the encapsulated data abstraction is created
    and initialised

71
Inheritance
  • To reuse an existing data abstraction the new
    data type is declared to be a subclass of the
    existing class
  • Operations on the existing data type are
    inherited by the new data type the new class can
    add data values and add or override operations
  • Inheritance carries the implicit assumption that
    subclasses are in fact subtypes the instances of
    the new abstraction react similarly as the
    instances of the existing abstraction
  • Proper creation and initialisation of the parent
    abstraction is language dependent
  • Private inheritance in C is appropriate here
    but breaks the substitutability principle

72
Composition and Inheritance Contrasted (1)
  • Composition is simpler what operations are
    supported by the data type is clear from the
    declaration only
  • Through inheritance the operations of the new
    data type are a superset of the operations on the
    original data type two or more declarations must
    be inspected to know the complete set (the yo-yo
    again)
  • Data abstractions constructed through inheritance
    are briefer, the implementations are shorter
  • Inheritance does not prevent users from
    manipulating the new data type with old
    operations breaching the information hiding
    principle leaving the values unprotected

73
Composition and Inheritance Contrasted (2)
  • In composition the existing data type becomes a
    storage mechanism for the new data type and thus
    just an implementation detail. It is easier to
    reimplement the data type with another technique
    with minimal impact on the users of the data type
  • Understandability and maintainability are
    difficult to judge. Inheritance has the advantage
    of brevity of code but the programmer must
    understand both classes. Composition code,
    although longer, is the only code the programmer
    must understand
  • Data structures implemented through inheritance
    have a very small advantage in execution time
    since one function call is avoided (use inline
    functions in C)

74
Subclasses and Subtypes
  • The concept of subclasssing is a way of
    constructing new software components using
    existing components.
  • The concept of subtyping is more abstract and has
    to do with behavior, not structure. What matters
    is substitutability
  • The concepts of subtype and subclass are not
    necessarily related. Two classes can respond to
    the same set of messages without any common
    implementation or common ancestor. If their
    response to the messages is sufficiently similar
    they can substitute for each other
  • Statically typed languages blur the distinction
    they assume that all subclasses are subtypes
    while this is not necessarily true when
    subclasses override the behavior of the parent

75
Variables and Values
define variable My-Card Card
define variable My-Card Card

define variable ltnamegt lttypegt
assign My-Card
make instance Magic Card spade, 4, true
assign ltvariablegt ltvaluegt
make instance Magic Card Spade, 4, true
76
Polymorphic Variables
  • In statically typed programming languages, the
    static type of a variable is fixed in the
    declaration statement while the dynamic type
    refers to the type of the value held by the
    variable
  • One of the more important features of statically
    typed object oriented languages is that the
    static and dynamic type of a variable must not
    match exactly a variable of type/class A can
    hold instances of any subtype/subclass of A.
    These variables are called polymorphic variables
  • In dynamically typed languages, all variables are
    in a sense polymorphic

77
Method Binding Static ltgt Dynamic
  • Should a message be bound to a method based on
    the static or dynamic type of the variable that
    is the receiver of the message?

Change-rank(1)
78
Method Binding
  • The difference is important when a method is
    overridden in the subclass
  • Most of the time binding the message to the
    dynamic type is what we expect but the opposite
    is sometimes useful

Window MouseDown(int,int)
TextEditWindow MouseDown(int,int)
Window W TextEditWindow T() W
T W.MousedDown(3,5)
79
Reverse Polymorphism
  • Can a instance of a subclass that is assigned to
    a variable with static type a superclass be
    assigned back to a variable with as static type
    the subclass?
  • The are two questions (1) can we tell whether
    the value is an instance of the subclass and (2)
    what mechanisms are necessary to assign the value
  • Is an important question when collections are
    considered

List
Set
Stack
List X Set Y Stack Z Set A() Stack B() X
A Y X X B Z X
80
Method Lookup in C (1)
  • A primary objective of C is space and time
    efficiency. Therefor most features are statically
    rather than dynamically bound
  • Variables can be polymorphic only when pointers
    or references are used
  • For "normal" variables method binding is static
  • For pointers or references dynamic method binding
    is used when the keyword virtual is used in the
    method declaration
  • Even in the latter case, the compiler will check
    the legality of the message send expression using
    the static class of the receiver

81
Method Lookup in C (2)
  • class Mammal
  • public void speak () printf ("can't speak")
  • virtual void bark () printf ("can't
    bark")
  • class Dog public Mammal
  • public void speak () printf("woef")
  • void bark () printf("woef also")

82
Method Lookup in C (3)
  • Mammal fred
  • Dog lassie()
  • fred lassie
  • fred.speak() cant speak
  • fred.bark() cant bark
  • Mammal fido
  • Dog fifi new Dog()
  • fido fifi
  • fido-gtspeak() "can't speak"
  • fido-gtbark() "woef also"

83
Reverse Polymorphism in C
  • A dynamic_cast can cast from a polymorphic
    base class to a derived class or a sibling class
    the operand must be polymorphic because run-time
    type information is needed which is not available
    for "normal" variables
  • fido2 dynamic_cast ltDog2 gt (fido1)
  • The typeid operator is used do discover the exact
    type of an object it returns a reference to a
    predefined type type-info typeid(fido1)
  • For diagnostic output, the name of a class can be
    recovered as a string form this type-info
    structure
  • typeid(fido1).name()

84
Method Lookup in Java
  • Messages are always bound to methods based on the
    dynamic type of the receiver
  • Data fields can also be overridden in Java but in
    this case binding of an access is based on the
    static type
  • Interfaces define a hierarchical organisation
    similar but independent from the class hierarchy.
    Interfaces can be used as types in variable
    declarations. Instances of classes that implement
    that interface can be assigned to these
    variables. The static type is then an interface
    type while the dynamic type is a class type.
    Method binding uses the dynamic type

85
Reverse Polymorphism in Java
  • In Java all variables know their dynamic type it
    is possible to test the type with the instanceOf
    operator
  • List L
  • if (L instanceOf Stack) ...
  • Reverse polymorphism is permitted with an
    explicit cast. When the cast is invalid an
    exception is thrown
  • Stack S
  • S (Stack) L

86
Method Lookup in CLOS
  • When a generic function is called the set of
    methods associated with the generic function is
    sorted to find/create an effective method. Three
    steps are taken
  • Select applicable methods the parameter
    specialiser is a class and the argument must be
    an instance of that class or one of its
    subclasses
  • Sort applicable methods every class has a class
    precedence list that orders the class and its
    superclasses, the class precedence list of the
    argument is used to order the applicable methods
    found
  • Apply method combination to the applicable
    methods

87
Class Precedence List
food beverage fruit sauce alcohol tomato
worchester bloody-mary
  • A class precedence list is calculated using the
    following guidelines
  • A class precedes its direct superclasses
  • The order in the defclass definition is
    maintained in case of multiple parents
  • Each superclass appears only once
  • If the hierarchy contains a cycle an error is
    returned

(bloody-mary tomato fruit worchester sauce food
alcohol beverage standard-object t)
88
Method Combination (1)
  • Standard method combination distinguishes primary
    methods and three kinds of auxiliary methods that
    modify the main action indicated by the
    qualifiers before after around
  • When all applicable methods are primary methods
  • the most specific primary method is called first
  • when other primary methods are available they can
    be called explicitly using the function
    call-next-method which will in each step invoke
    the next most specific primary method
  • the next-method-p predicate checks whether the
    next most specific method exists
  • the value returned by the most specific primary
    method is the value returned by the generic
    function

89
Method Combination (2)
  • When both primary and auxiliary methods are
    involved
  • the most specific around method is called and
    call-next-method can be used to invoke the next
    most specific around method
  • when there are no more around methods call-next
    method will call every applicable before method
    in order
  • after the last before method the most specific
    primary method is called which in turn can use
    call-next-method to invoke other applicable
    primary methods
  • when the effective primary method exits all the
    after methods are called in order
  • before and after methods are used for
    side-effect, the value they return is ignored

90
Method Combination Overview
R1 R1 R2 R2 B1 B2 B3 P1 P3 A2 A1
P2 P2 P3
call to call-next-method Ri around return
from call-next-method Ai after methods called
in sequence Bi before Pi primary
91
Method Combination Example (1/1)
  • (defclass person ()
  • ((name initarg name reader name)))
  • (defclass phd-holder (person) ())
  • (defclass professor (phd-holder) ())
  • (defmethod printname ((p person))
  • (format t (name p)))
  • (defmethod printname ((p phd-holder))
  • (format t "Dr. ")
  • (call-next-method))
  • (defmethod printname ((p professor))
  • (format t "Prof. ")
  • (call-next-method))

92
Method Combination Example (2/1)
  • ? (setf bob (make-instance 'person
  • name "Bob Brown"))
  • ltPERSON x202A6D6gt
  • ? (setf viv (make-instance 'professor
  • name "Viviane Jonckers"))
  • ltPROFESSOR x202A876gt
  • ? (printname bob)
  • Bob Brown
  • NIL
  • ? (printname viv)
  • Prof. Dr. Viviane Jonckers
  • NIL

93
Method Combination Example (1/2)
  • (defclass employe ()
  • ((name initarg name reader name)
  • (salary initarg salary accessor salary)
  • (department initarg department
  • accessor department)))
  • (defclass department ()
  • ((name initarg name reader name)
  • (expenses initarg expenses
  • accessor expenses initform 0)
  • (manager initarg manager
  • accessor manager)))

94
Method Combination Example (2/2)
  • (defmethod give-raise ((e employe) amount)
  • (setf (salary e) ( (salary e) amount)))
  • (defmethod give-raise around ((e employe)
    amount)
  • (if (gt ( (salary e) amount) (salary (manager
    (department e))))
  • (format t "cannot give raise")
  • (call-next-method)))
  • (defmethod give-raise before ((e employe)
    amount)
  • (setf (expenses (department e)) ( (expenses
    (department e)) amount)))
  • (defmethod give-raise after ((e employe) amount)
  • (format t "raise is given"))

95
Method Combination Example (3/2)
  • ? (setf sales (make-instance 'department name
    'sales))
  • ltDEPARTMENT x202D476gt
  • ? (setf bill (make-instance 'employe name "bill
    gates" salary 40000 department sales))
  • ltEMPLOYE x202D66Egt
  • ? (setf bob (make-instance 'employe name "bob
    brown" salary 30000 department sales))
  • ltEMPLOYE x202D866gt
  • ? (setf (manager sales) bill)
  • ltEMPLOYE x202D66Egt

96
Method Combination Example (4/2)
  • ? (give-raise bob '5000)
  • raise is given
  • 35000
  • ? (salary bob)
  • 35000
  • ? (expenses sales)
  • 5000
  • ? (give-raise bob '10000)
  • cannot give raise
  • NIL

97
Replacement and Refinement
  • When a subclass simply adds data or methods to a
    super-class the data and methods of parent and
    child are distinct
  • When a subclass overrides data or methods of a
    parent class both replacing and refining
    semantics are possible
  • Method replacement implies that code from the
    parent is never executed when manipulating
    instances of the child
  • With method refinement the method inherited from
    the parent is executed as a part of the execution
    of the child's method
  • Refinement of data can mean different things
    have both or combine defaults and other options

98
Replacement and Substitutability
  • Replacement semantics do not fit with the
    substitutability principle when subclasses are
    free to override existing methods with methods
    that can perform arbitrary actions there is no
    guarantee that the behavior of the child class
    will be anything like the behavior of the parent
    class
  • Most languages ignore the problem and leave it to
    the programmer to do the right thing
  • In Eiffel a programmer can attach assertions
    (conditions on the object's state) to a method.
    Assertions are inherited and enforced even if the
    actual method is overwritten

99
Refinement
  • Refinement semantics solve the conflict between
    overriding and substitutability rather than
    replacing the code of the parent class, the
    actions described in the child class are combined
    with the actions described in the parent class
    ensuring a minimum level of functionality
  • The desirability of refinement semantics is most
    apparent in the creation of new objects the
    initialisations of both the parent class and the
    child class must take place
  • Most languages support refinement semantics
    through a mechanism that allows an overridden
    method to invoke the same method in the parent
    class

100
Replacement in C
  • Overriding in C is complicated by the
    intertwining with overloading and the virtual/non
    virtual declaration of methods
  • Simple replacement occurs only when the arguments
    in a child class method match type and number of
    the arguments in the parent class exactly and
    when the method is declared virtual
  • Without the first condition overloading takes
    over there are two distinct methods
  • Without the second condition method binding is
    static, so it is the parent class method that is
    executed anyhow

101
Refinement in C
  • In C a method invocation can be qualified to
    precisely specify the class from which the method
    is to be derived. The qualification is written as
    classnamemethodname
  • Qualification can be used to simulate the
    mechanics of refinement in overriding an
    overridden method can explicitly invoke the
    method of the parent class ensuring that both
    will be executed
  • Constructors always use refinement rather than
    replacement the constructor of the parent class
    can be invoked explicitly though an
    initialisation clause in the constructor of the
    child class, if not the default constructor of
    the parent is invoked

102
Replacement and Refinement in JAVA
  • Replacement occurs when a method has the same
    signature as a method in the parent class
    otherwise overloading takes over
  • Data fields can be replaced or shadowed but the
    replacements are not dynamic, the data field
    selected will be determined by the static type
    (class) of a variable, not by its dynamic type
  • The keyword final can explicitly disallow
    overriding
  • The pseudo-variable super provides the mechanism
    for simulating refinement

103
Replacement and Refinement in CLOS
  • The method combination mechanism explained before
    can simulate refinement semantics through the use
    of call-next-method. Without a call to
    call-next-method, replacement semantics occur
    since in the standard method combination
    mechanism the most specific method will be the
    effective method
  • Both local and shared slots can be overwritten or
    shadowed. Slot-options and class-options are
    appropriately combined when instances are created

104
Multiple Inheritance
  • Many non overlapping classification for a single
    entity are possible being European, female,
    teacher, parent, etc
  • Multiple inheritance is appropriate when the
    "is-a" relation-ship holds a portrait-painter is
    a painter and is an artist
  • Single inheritance has often a specialisation
    flavor, multiple inheritance has a combination
    flavor
  • Multiple inheritance is a powerful and useful
    feature in a languages but creates many and
    subtle problems for the language implementor

105
Name Ambiguity (1)
  • Two meanings of draw clash draw a card from a
    pile of cards and draw a graphical object on a
    screen
  • The problem is with the child class, not with the
    parent classes
  • A combination of renaming and redefinition is the
    standard solution in this case

GraphicalObject Draw
CardDeck Draw
GraphicalDeck
106
Name Ambiguity (2)
  • A single conceptual meaning for AccessPriv and
    PrintTitle but a different value or method in
    each parent class
  • Renaming is probably not the preferred solution
    a mechanism is needed to let the child class
    decide on precedence or combination style

Student AccessPriv PrintTitle
Teacher AccessPriv PrintTitle
TeachingAssistant
107
Inheritance from Common Ancestors
Person Name PrintTitle
  • When only behavior is inherited from the common
    parent the usual resolution techniques can be
    used
  • When data fields are involved, it must be decided
    whether a data field is inherited once or twice
    and whether constructors and initialisations must
    be invoked once or twice

Teacher PrintTitle
Student PrintTitle
Teaching-Assistant
108
Multiple Inheritance in C
  • Both renaming and combination of methods can be
    achieved through qualification
  • class GraphicalDeck public GraphicalObject,
    public CardDeck
  • public void Draw() GraphicalObjectDraw()
  • Card ChooseCard() CardDeckDraw()
  • ...
  • class TeachingAssistant public Teacher, public
    Student
  • public PrintTitle() TeacherPrintTitle()
  • Print(" ")
  • StudentPrintTitle()
  • ...

109
Multiple Inheritance and Parametric Overloading
in C
  • In C methods with the same name but different
    signatures are distinct. The compiler picks the
    right one based on the actual arguments in the
    call.
  • When two parent classes define a method with the
    same name but a different type of parameter one
    would expect the child class to inherit both
    (distinct) methods
  • But the compiler cannot decide between the method
    that fits the argument type best and the method
    that is found first in the method search
    procedure and is applicable with implicit
    parameter conversion therefor an error will be
    thrown

110
Multiple Inheritance in Java
  • Java does not support multiple inheritance as
    such, but
  • a class can implement multiple interfaces
  • an interface can extend multiple interfaces
  • a class can extend another class and implement an
    interface
  • When a class implements multiple interfaces, name
    clashes do no harm since the implementation of
    the method is provided in the class definition
    anyhow

111
Multiple Inheritance in CLOS
  • The method combination mechanism explained before
    implements precisely a standard form of method
    combination
  • When the standard method combination mechanism
    does not produce the intended results, new types
    of method combination can be specified though the
    use of the (very sophisticated but also very
    complicated) define-method-combination macro

112
Memory Layout and Inheritance
  • How much space must be allocated for a variable
    of type Window ?
  • Three possible answers
  • Minimal static space allocation
  • Maximal static space allocation
  • Dynamic memory allocation (use one pointer)

Window int height int width
TextWindow char contents int cursorlocation
113
Minimal - Maximal Static Space Allocation
  • Allocate space for the base class data fields
    only
  • Used in C for non-pointer and non-reference
    variables that are allocated on the stack
  • When assigning an instance of the (larger)
    subclass to a variable with the base class as
    static type some data is lost
  • This loss is never problematic since method
    binding is static on these variables
  • Allocate space for the largest of any values the
Write a Comment
User Comments (0)
About PowerShow.com