You are on page 1of 11

COMMONWEALTH OF AUSTRALIA

FIT2005 Software Analysis, Design & Architecture

Copyright Regulations 1969 WARNING This material has been reproduced and communicated to you by or on behalf of Monash University pursuant to Part VB of the Copyright Act 1968 (the Act).

Module 5: Inheritance and Polymorphism


www.monash.edu.au

The material in this communication may be subject to copyright under the Act. Any further reproduction or communication of this material by you may be the subject of copyright protection under the Act. Do not remove this notice.
2

Module 5 Objectives
On completion of this session you should have a conceptual understanding of: inheritance, generalisation, specialisation, overriding, abstract operators and classes; Complete and incomplete generalisation sets; Disjoint and overlapping generalisation sets; Levels of abstraction; Polymorphism of operations and of variables

Module 5 Objectives (continued)


On completion of this module you should be able to:
Employ inheritance techniques to use one class as a basis for further refined classes to design the static structure of the system; Employ polymorphism techniques to design the behavioural aspects of the system; Identify problems in a proposed static structuring of classes and explain possible solutions to those problems; Partition classes using generalisation sets; and

Inheritance
Inheritance is a technique in programming where a derived class extends the functionality of a base class, inheriting all of its state and behavior Arises where a class is refined into a more-specific type.
Can be given an extended set of features Can have additional or even replacement operations

Generalisation
Generalisation a (cognitive) process of considering which features of a class can be moved into a more abstract version of the class to form the basis for potential other derived classes Specialisation the inverse process: using one class as the basis from which to make a special version of that class that refines the classs purpose to a particular focus Generalisation Relationship a relationship between a more general element and a more specific element where the more specific element is entirely consistent to the general element
Thus conforming to the substitutability principle
5 6

Substitutability Principle objects of the more refined class type can be used anywhere that the more general class type is expected (e.g. in associations)

Class Generalisation
Progressive refinement of classes Based on similarities Preserves differences Superclass
The more abstract class

Generalisation relationships
A child class is-a kind of the parent class
E.g. a horse is a kind of animal. Objects of the child class can be substituted for the parent but not the reverse

A class with no parents is a base class A class with no children is a leaf class

Subclass
refined class, more concrete/detailed

Ancestor or descendant
generalised classes across multiple levels

UML Notation for Generalisation: a line connecting two classes with a hollow triangle at the superclass end

Class Generalisation Real-world Example

Class Generalisation Software Example

Superclass of Bus

Vehicle

Ancestor of Utility
..

Superclass of UnitCost

AbstractCost

Ancestor of GST (Goods and Services Tax)

Subclasses of Vehicle

Truck

Car

Bus

Subclasses of AbstractCost

UnitCost

TaxCost

MarkupCost

..

Subclasses of Car

Sedan

Coupe

Utility

Descendant of Vehicle

Subclass of Tax

GST

LuxuryCarTax

Descendants of AbstractCost

GST means Goods and Services Tax


9 10

Inheritance
The Subclass: inherits all features (i.e. attributes, operations, states, relationships, constraints) of its superclass may vary the methods (i.e. implementations) for operations Can add further specific attributes and operations

Inheritance
allows sharing of definition of attributes and operations through generalization purpose is for the conceptual simplification of reducing the number of independent features facilitates code re-use Can be done for extension - new features are added in subclass Can be done for restriction - subclass constrains values which attributes can have
e.g. PositiveInteger as a subclass of Integer

Avoid deep nesting of generalization

11

12

Identifying Potential Generalisations


Sometimes a group of objects shares some common attributes and/or methods, but other attributes and/or methods are distinct
Bicycles and cars are both vehicles, both have wheels and both can stop, start and turn Cars have doors, windows and fuel tank, but bicycles dont Bicycles have pedals and handlebars but cars dont Cars are powered by fuel burning whereas bicycles are powered by pedalling

Identifying Potential Generalisations


Consider there are already two classes: Bicycle and Car Should the common members (attributes, methods) of different classes be duplicated in completely separate classes?

Bicycle wheels gears handles pedals start() stop() turn() pedal()

Car wheels gears windows doors tank start() stop() turn() burn()

13

14

Identifying Potential Generalisations


It is better to define common members in a general, parent or super class Child or sub classes can inherit common members from parent class Child classes can have specific members Car windows doors tank fill() burn()
15

Your Turn
Place animals with common kinds of behavior into groups

Vehicle wheels gears start() stop() turn()

UML generalisation representation

Bicycle handles pedals pedal()

16

Grouped based on common behaviors

Abstract Operations and Classes


Abstract Operation an operation where the implementation is deferred to subclasses

fly() hop() slither()

Signified by writing operation in italics (cf. concrete operation not in italics)

Abstract Class a class which is incomplete, usually because it has some abstract operations
Signified by writing name in italics

Models may still utilise abstract classes and operations


E.g. use a Shape in the sequence diagram, but at run-time it could really be a Circle that is substituted.

walk() & run() swim()


17 18

Over-riding
subclass may over-ride inherited features, but must preserve the signature of each feature Signature The operation name, its return type, and the types of all the parameters listed in order. Effect is to provide a different response to the same message when compared to the superclass Example:
A Shape class with subclasses for Square, Circle, Triangle The draw and getArea methods of Shape will need to be overridden by the subclasses

Example of Inheritance in Code (1)


public class BankAccount { private float balance; public BankAccount() { balance = 100; } public float withdraw(float amount) { if ( (balance amount) > 0) balance = balance amount; return balance; } public void deposit(float amount) { balance = balance + amount; } }
19 20

Example of Inheritance in Code (2)


Signifies that SavingsAccount is a subclass of BankAccount

Polymorphism
Polymorphism means many forms 2 aspects:
Redefined implementation of an inherited operation

public class SavingsAccount extends BankAccount { private static float FEE = 2.95;

public float withdraw(float amount) { if ( (balance amount - FEE) > 0) balance = balance amount - FEE; return balance; } }

Polymorphic operation: Polymorphism is the facility by which a single operation or attribute name may be defined upon more than one class and may take on different implementations in each of those classes. (Page-Jones, p. 38) Polymorphic reference/variable: Polymorphism is the property whereby an attribute or variable may point to (hold the handle of) objects of different classes at different times. (ibid)

This class inherits the deposit operation from BankAccount It re-defines the withdraw operation with its own method It extends BankAccount with additional values (FEE)
21

The response for a given message depends on the particular type of object which actually receives the message

22

Polymorphism (2)
Consider classes Square and Circle as having a common parent class: Shape. The getArea operation can be abstract in the Shape class The Square class can provide its own concrete implementation which calculates: width * height The Circle class can provide its own concrete implementation which calculates: r2

Polymorphism (3)
Visual Paradigm for UML Standard Edition(Monash University)

driver : Driver

shape : Shape

1: getArea() : double

An interaction sequence can show a getArea message being sent to a Shape lifeline, but that Shape will be representing either a Square or Circle object
One or the other objects implementation will be done. getArea is called the trigger contrasted to the response which depends on the actual Shape (either Square or Circle) The response is polymorphic (its own unique sequence of messages)
23 24

Polymorphism Example: Bank Accounts


Visual Paradigm for UML Standard Edition(Monash University)

Polymorphism Example: Bank Accounts (cont.)


Visual Paradigm for UML Standard Edition(Monash University)

Bank 1 *

Account -balance : Real +withdraw(amount : Real) +calculateInterest() +deposit(amount : Real)


Teller

bank : Bank

source : Account

destination : Account

transfer(source,destination,amount)

withdraw(amount)

deposit(amount)

SavingsAccount +withdraw(amount : Real) +calculateInterest()

ChequeAccount +withdraw(amount : Real) +calculateInterest()

The particular kind of account which is used in each case does not matter because polymorphism will ensure appropriate behaviour occurs for each object in response to the triggers. We do not usually show the response of these polymorphic triggers (because the response varies)

25

26

Generalization Sets
Consider the following shapes
FIT2005 Software Analysis, Design & Architecture

Source: Arlow Fig 10.11

Advanced topics in Generalisation


How might we partition them the form a generalisation hierarchy?
www.monash.edu.au
28

Generalization Sets (2)


The previous slide shows two distinctly different groups of Shape. A possible model for this situation is to use generalization sets:
Source: Arlow Fig 10.12

Generalization Sets (3)


Constraints can be applied to generalization sets: {complete} Indicates that the subclasses shown in the set show all possibilities {incomplete} There may be subclasses besides those shown {disjoint} An object will be an instance of only one of the members of the general set {overlapping} An object can be (simultaneously) an instance of more than one of the members of the set

Most common case is: {incomplete, disjoint}


29 30

Generalization Sets examples

Generalization Sets examples (2)

Source: Rumbaugh
31

Source: Rumbaugh
32

Level of Abstraction
All peers in a generalization hierarchy should be at the same level of abstraction Example of classes not at same level of abstraction:
Fruit

Level of Abstraction
All peers in a generalization hierarchy should be at the same level of abstraction Now apple is at the same level as apricot and peach:
Fruit

StoneFruit

Apple

Apple should be a level lower than it is since it is not a contrast to all Stone Fruits

StoneFruit

SeedFruit

Peach

Apricot

Peach

Apricot

Apple

34

33

Multiple Inheritance
class with more than 1 parent class inherits all features of all parents - possible conflicts which must be resolved not always supported by all Object Oriented languages
Vehicle

Common Mistakes (1)


What is wrong with the following model of an Airplane?
Airplane
Adapted from Page-Jones: Figure 12.1

Wing

Tail

Engine

Fuselage

Land Vehicle

Water Vehicle

This says that a Wing is a type of Airplane, etc.

Car

Hovercraft

Ferry Boat

35

36

Common Mistakes (2)


What is wrong with the following alternative model of an Airplane?
Wing Tail Engine Fuselage

Common Mistakes (3) Inverted Hierarchy


What is wrong with the following?
BoardMember

Airplane

Adapted from Page-Jones: Figure 12.1

Manager

Adapted from Page-Jones: Figure 12.2

This says that an Airplane is a type of wing, and a type of tail, etc. But, really, an airplane has a wing, a tail, etc
37

Worker

Although it may look right, according to an organisational chart, it is not semantically correct if using UML notation. Arrows should go in opposite direction.
38

Common Mistakes (4)


What is wrong with the following?
Bear EndangeredSpecies
Adapted from Page-Jones: Figure 12.3

Panda Example Better Solution

Panda

The two superclasses are at different levels of abstraction The Endangered-ness is really an attribute, and not an integral part of the identity of the Panda class
39

Source: Page-Jones

40

Readings
Prescribed:
Arlow Chapter 10 Page-Jones Chapter 12 (in Unit Reader)

41