You are on page 1of 66

Software Engineering

Lecture 1:
Type hierarchy
2013

Outline
Type hierarchy: why & what?
Type hierarchy features
Create a type hierarchy
Subtypes with attributes
Abstract class (overview)
The meaning of subtype
Multiple implementations
Using a type hierarchy
2013

FIT330 Software Engineering

Why type hierarchy?

Similarities exist among types that require a


higher level of abstraction...

2013

FIT330 Software Engineering

Example: vehicles
P

...

Car

Bus

2013

Airplane

FIT330 Software Engineering

Example: vehicles (2)


P

...

Car

Bus

2013

Airplane

FIT330 Software Engineering

Example: vehicles (3)


P

...

Car

Bus

2013

Airplane

FIT330 Software Engineering

Example: vehicles (4)


P

?
...

Car

2013

Bus

FIT330 Software Engineering

Airplane

What is a type hierarchy?


A product of type abstraction
A hierarchy of types in which higher-level types
are abstractions of lower-level ones

2013

FIT330 Software Engineering

Benefits
Enhance ability to solve real world problems
Program modifiability:

2013

multiple implementations of a type

FIT330 Software Engineering

One-level TH example: vehicles


Vehicle

Bus

2013

Car

FIT330 Software Engineering

...

10

Two-level TH: vehicles


Vehicle

Road
Vehicle

Bus

2013

Car

...

Airplane

FIT330 Software Engineering

Air
Vehicle

...

Space
shuttle

IronMan

...

11

Multi-level TH: exceptions


Throwable
Error

Exception
RuntimeException

(checked exceptions)

(unchecked exceptions)

2013

FIT330 Software Engineering

12

What about multiple super types?


A subtype can have more than one supertypes
In Java:

2013

only one super type is class, others must be


interfaces

class: specification and code

interface: specification only

FIT330 Software Engineering

13

Example
Interface PriorityVehicle represents
vehicles with priorities
Vehicle

PriorityVehicle
<<implements>>
Bus

2013

FIT330 Software Engineering

Car

14

Example: List TH
List is a sequence of elements
Two basic orders:

insertion

sorted: ascending or descending

Java interface: java.util.List


Two subtypes:

2013

ArrayList

LinkedList

FIT330 Software Engineering

15

List TH
Includes both classes and interfaces
<<interface>>
Collection

Queue

Abstract
Collection

List

AbstractList

ArrayList
2013

FIT330 Software Engineering

LinkedList

Vector
16

Type hierarchy features

May extend through many levels


Inheritance principle
Abstraction by specification
Subtypes typically override certain behaviour
Subtypes can extend supertype's behaviour

2013

FIT330 Software Engineering

17

Inheritance
Subtypes inherit attributes and operations of
the supertype and all ancestors (except
constructors):

benefit: code re-use

Sub-types must define constructors that they


wish to use:

but must invoke suitable supertype constructor(s)


if not the default

Objects of the subtypes must not violate


properties associated to the attributes:

2013

see properties rule


later
FIT330 Software Engineering

18

Example: Vehicle TH with details


Vehicle

Setters/
getters
of other
attributes
are omitted

2013

- String name
- double width
- double height
- double length
- double weight
- int seatingCapacity
+ Vehicle(String, double, double, double, double, int)
+ getName(): String
+ setName(String)
+ calcTotalWeight(): double
+ repOK(): boolean
+ toString(): String
- validate(String, double, double, double, double, c): boolean
- validateName(String): boolean
- validateDimension(double): boolean
# validateWeight(double w): boolean
# validateSeatingCapacity(int c): boolean
FIT330 Software Engineering

19

Vehicle
- name: String
- width: double
- height: double
- length: double
- weight: double
- seatingCapacity: int
+ Vehicle(String, double, double, double, double, int)
+ getName(): String
+ setName(String)
+ calcTotalWeight(): double
+ repOK(): boolean
+ toString(): String
- validate(String, double, double, double, double, c): boolean
- validateName(String): boolean
- validateDimension(double): boolean
# validateWeight(double w): boolean
# validateSeatingCapacity(int c): boolean

Bus

Car

+ Bus(String, double, double, double, double, int)


+ toString(): String
# validateWeight(double w): boolean
# validateSeatingCapacity(int c): double
2013

+ Car(String, double, double, double, double, int)


+ toString(): String
# validateWeight(double w): boolean
# validateSeatingCapacity(int c): double

FIT330 Software Engineering

20

Usage
// create objects
Vehicle v1 = new Bus("b1",3.0,3.0,10.0,6000,40);
Vehicle v2 = new Car("c1",1.5,1.5,2.5,1500,4);
// use objects
System.out.println("Vehicle " + v1.getName() +
", weight: " + v1.calcTotalWeight());

Substitution principle:
super type variable can be assigned
to subtype objects
2013

FIT330 Software Engineering

21

Create a type hierarchy


Specify
Implement

2013

FIT330 Software Engineering

22

Specify supertype & subtypes


Specify a supertype with common behaviour
Specify each subtype relative to the supertype:

use extends or implement keyword

specify new or overriding behaviour

may specify new attributes

abstract properties are defined based on


supertype's:

so are AF and rep invariant

Annotate overriding operations with


@Override
2013

FIT330 Software Engineering

23

Class/interface rules
Supertype/subtype class or interface
Object is the (root) supertype of all types
Interface only has specifications
Interface can only be a subtype of another
interface
Class can be a subtype of:

2013

one class and/or

multiple interfaces

FIT330 Software Engineering

24

Vehicle
ch7.vehicles.Vehicle
Note:

2013

rep invariant omitted (property statements are


easy to code directly)

constant DomainConstraint.ZERO_PLUS

two validation methods are declared protected:

validateWeight

validateSeatingCapacity

FIT330 Software Engineering

25

Bus
ch7.vehicles.Bus
Note:

rep invariant omitted

constructor is redefined (not inherited)

P_Vehicle: abstract properties of Vehicle

2013

abstract properties = Vehicle's + two new


constraints on weight and seatingCapacity
override two protected validation methods:

validateWeight

validateSeatingCapacity
FIT330 Software Engineering

26

Car
ch7.vehicles.Car
Note:

2013

Car is specified in a similar manner, except for the


constraints on weight and seatingCapacity

FIT330 Software Engineering

27

Bus is a PriorityVehicle
Vehicle

PriorityVehicle
<<implements>>
Bus

2013

FIT330 Software Engineering

Car

28

PriorityVehicle
ch7.vehiclesintf
.PriorityVehicle
.Bus
Note:

2013

Bus uses the implement keyword

FIT330 Software Engineering

29

Implement a TH in Java
Keyword super refers to supertype's members
Implementation can be full or partial

abstract class is partial (later)

Representation includes protected attributes


of super
Overriding repOK must invoke super.repOK
Immutable subtypes with extra state variables
must override equals (later)

2013

FIT330 Software Engineering

30

Vehicle
ch7.vehicles.Vehicle
Note:

2013

repOK invokes validate

toString uses Vehicle prefix

FIT330 Software Engineering

31

Bus
ch7.vehicles.Bus
Note:

2013

constructor invokes super constructor

toString uses Bus prefix

validation methods check against the min values

FIT330 Software Engineering

32

Car
ch7.vehicles.Car
Note:

2013

constructor invokes super constructor

toString uses Car prefix

validation methods:

invoke super's validation methods and

check against the max values

FIT330 Software Engineering

33

PriorityVehicle
ch7.vehiclesintf
.PriorityVehicle
.Bus
Note:

2013

Bus uses the implement keyword


comparePriorityTo invokes other methods to
get data

FIT330 Software Engineering

34

Subtypes with extra attributes

Subtypes can have their own attributes


Design specification of the subtype needs to
take into account these attributes:

2013

class header specification: attributes, abstract


properties, abstraction function, rep invariant
constructors may need to take extra argument(s)
(depending on domain constraint(s))
new operations may be needed, e.g. getter/setter
supertype's operations may need to be overriden
(details later)
FIT330 Software Engineering

35

Example:
Vehicle TH

Vehicle
- name: String
- width: double
- height: double
- length: double
- weight: double
- seatingCapacity: int
+ Vehicle(String, double, double, double, double, int)
...
+ repOK(): boolean
+ toString(): String

# validateWeight(double w): boolean


# validateSeatingCapacity(int c): boolean

Bus

Car

- routes: int[]

- owner: String

+ Bus(String, double, double, double, double, int, int[])


+ getRoutes(): int[]
+ repOK(): boolean
+ toString(): String
# validateWeight(double w): boolean
# validateSeatingCapacity(int c): boolean
- validateRoutes(): boolean

+ Car(String, double, double, double, double, int)


+ setOwner(String)
+ getOwner(): String
+ repOK(): boolean
+ toString(): String
# validateWeight(double w): boolean
# validateSeatingCapacity(int c): boolean
- validateOwner(): boolean

2013

FIT330 Software Engineering

36

Bus
ch7.vehiclesextra.Bus
Note:

abstract properties use function length over array

rep invariant omitted

constructor takes an extra argument

getRoutes: return a copy of routes

2013

repOK: first invoke super's then invoke


validateRoutes
validateRoutes: validate routes against
abstract properties
FIT330 Software Engineering

37

Car
ch7.vehiclesextra.Car
Note:

2013

abstract properties use function length over


string
rep invariant omitted
setOwner: validate argument by invoking
validateOwner before setting
repOK: first invoke super's then invoke
validateOwner
validateOwner: validate owner against abstract
properties
FIT330 Software Engineering

38

The meaning of subtype


Based on the substitution principle:

supertype can be used in place of its subtypes

Subtype specification must satisfy three


substitution rules:

2013

header rule

methods rule

properties rule

FIT330 Software Engineering

39

Subtype can override supertype method given


that the overriding method satisfies both:

header rule

methods rule

More details on method overriding later

2013

FIT330 Software Engineering

40

When to override?
When to override a method in a subtype?
To take into account:

subtype's type information

values of subtype's attributes

Example:

2013

ch7.vehiclesextra.Bus,Car

Point3.equals (later)

FIT330 Software Engineering

41

Header rule
Overriding methods must be header
compatible
Method header includes:

signature: method name, number and types of


parameters

return type

thrown exceptions: (details next lecture)

Compatibility means:

2013

same signature

return type: same (Jdk < 1.4) or subtype (>= 1.5)

exceptions: (details
next lecture)
FIT330 Software Engineering

42

Example: Vehicle.toString
@Override
public String toString() {
return "Vehicle(" + name + ")";
}

2013

FIT330 Software Engineering

43

Methods rule
Pre-condition (@requires) is the same or
weaken:

Presuper Presub

Post-condition (@effects) is the same or


strengthen:

2013

(Presuper && Postsub) Postsuper

FIT330 Software Engineering

44

Example

2013

Vector

IntSet

SortedIntVector

SortedIntSet

FIT330 Software Engineering

45

Vector.add
/**
* @effects appends o to the end of this
*/
@Override
public boolean add(Object o)

2013

FIT330 Software Engineering

46

SortedIntVector.add
/**
* @effects <pre> if this is empty OR o is >= all elements
*
of this
*
super.add(o)
*
else
*
insert o at the position i in this s.t
*
xk <= o for all 0 <= k <= i-1 and
*
xj > o for all i+1 <= j < this.size
*
</pre>
*/
@Override
public boolean add(Object o)

Is this a correct overriding method


2013

FIT330 Software Engineering

?
47

IntSet.insert
/**
* @modifies <tt>this</tt>
* @effects
adds x to this, i.e.
*
</tt>this_post = this + {x}</tt>
*/
public void insert(int x)

2013

FIT330 Software Engineering

48

SortedIntSet.insert
/**
* @modifies <tt>this</tt>
* @effects
<pre>adds x to this, i.e.
*
this_post = this + {x},
*
such that x is greater than all elements
*
before and smaller than all elements
*
after it</pre>
*/
@Override
public void insert(int x)

Is this a correct overriding method


2013

FIT330 Software Engineering

?
49

Properties rule
Subtypes must preserve the supertype's
properties
Properties are explicitly stated in @overview:

rep invariant

evolution

Rep invariant: subtype methods must not


change
Evolution: immutability

2013

FIT330 Software Engineering

50

Overriding equals
Point2 represents points on a plane
Point3

a subtype of Point2

represents points in space

override equals to take into account the third


dimension

Two techniques:

2013

Inheritance preserving

Non-inheritence preserving
FIT330 Software Engineering

51

Inheritance preserving
class Point2 {
private int x; // x-coordinate
private int y; // y-coordinate
p can be of
public boolean equals(Object p) {
if (p instanceof Point2) {
Point2 or
// overriden behaviour
any of
return this.equals((Point2) p);
its subtypes
} else {
// default equal behaviour (last resort)
return super.equals(p);
}
}
public boolean equals(Point2 p) {
return (p != null && x == p.x && y == p.y);
}
}
2013

FIT330 Software Engineering

52

Overriding equals
class Point3 extends Point2 {
private int z; // the z coordinate
public boolean equals (Object p) {
if (p instanceof Point3) {
// overriden behaviour
return this.equals((Point3) p);
} else {
// supertype's equal behaviour
return super.equals(p);
}
}

considers the
extra z
dimension

public boolean equals(Point3 p) {


return (p != null && super.equals(p) && z == p.z);
}
}
2013

FIT330 Software Engineering

53

Non-inheritance preserving
class Point2 {
private int x; // x-coordinate
private int y; // y-coordinate

p must be of
Point2
(subtypes not
comparable)

public boolean equals(Object p) {


// equal based on same class
if (p == null || p.getClass() != this.getClass())
return false;
return equals((Point2) p);
}
public boolean equals(Point2 p) {
return (p != null && x == p.x && y == p.y);
}
}
2013

FIT330 Software Engineering

54

Overriding equals
class Point3 extends Point2 {
private int z; // the z coordinate

p must be of
Point3
(sub/supertypes
not comparable)

public boolean equals(Object p) {


// equal based on same class
if (p == null || p.getClass() != this.getClass())
return false;
return this.equals((Point3) p);
}

public boolean equals(Point3 p) {


return (p != null && super.equals(p) && z == p.z);
}
}

2013

FIT330 Software Engineering

55

Abstract class
A super-type that cannot be instantiated

though still have constructors

Provides either partial or full implementation


Partial implementation must contain abstract
methods
Typically has rep invariant but no AF
Which class in the Vehicle TH
would be made abstract
2013

FIT330 Software Engineering

?
56

Multiple implementations
A restricted TH: subtypes have same behaviour
Subtype is an implementation of the supertype
Using code is written using supertype except for
creating objects
Subtypes are placed in the same package
Subtypes may refer to one another

2013

FIT330 Software Engineering

57

Example: Vehicle
Vehicle

Bus

Car

Bus and Car:

2013

have same behaviour


provide concrete implementations
FIT330 Software Engineering

58

What about this?


Vehicle

PriorityVehicle
<<implements>>
Bus

Is this TH a multi-implementation TH
2013

FIT330 Software Engineering

Car

?
59

or this?
Comparable

Vehicle

Bus

Car

Is this TH a multi-implementation TH
2013

FIT330 Software Engineering

?
60

Using a type hierarchy

Variable assignment rule


Dispatching

2013

FIT330 Software Engineering

61

Variable assignment rule


A variable of a supertype can be assigned to
objects of subtypes:

supertype: apparent type of the variable

subtype: actual type of the variable

Example:
Vehicle vb = new Bus(...);

2013

FIT330 Software Engineering

62

Dispatching
A run-time mechanism to find the right object to
execute a method
Each object has a pointer to a dispatch vector
Dispatch vector contains references to the
object methods
Method invocation is dispatched to the target
implementation

2013

FIT330 Software Engineering

63

Dispatching example
Stack

Heap
equals

o
r

<,abc>

Code for
String equals

<,abc>
Dispatch
vector

String t = "ab";
Object o = t + "c";
String r = "abc";
boolean b = o.equals(r);
2013

FIT330 Software Engineering

64

Summary
THs make program structure easier to
understand
THs enables shared specification for the
related types
THs supports extensibility
Subtypes obey the substitution principle

2013

FIT330 Software Engineering

65

Questions?

2013

FIT330 Software Engineering

66

You might also like