1 Object Oriented Programming Development - Week7 z Rob Manton z Email: [email protected] z...

53
1 Object Oriented Programming Development - Week7 Rob Manton Email: [email protected] k Room D104

Transcript of 1 Object Oriented Programming Development - Week7 z Rob Manton z Email: [email protected] z...

1

Object Oriented ProgrammingDevelopment - Week7

Rob Manton

Email: [email protected] D104

2

Module Outline

IntroductionNon object

oriented basicsClasses

InheritanceAggregationPolymorphismMultifile

Development

3

Today:

Timing of the practical test in week 9

Advice for lab sessions

Classes & Objects recap

Inheritance

4

Practical Test in Week 9

Who already has a lecture/practical on

Tuesday 26th November 5-8pm

Wednesday 27th November 5-8pm

Thursday 28th November 5-8pm

5

Advice for lab sessions

Create a ‘hello world’ project instead of an

empty one

type a line or two of code then compile - this

should make it easier to identify and fix syntax

problems

When writing a class or method add the

opening and closing braces/semicolon and

compile before ‘fleshing out’.

6

Advice for lab sessions

#include "stdafx.h"

int main(int argc, char* argv[]){

printf("Hello World!\n");return 0;

}

The skeleton program you

get from a ‘hello world’ project

7

Advice for lab sessions

#include "stdafx.h"

int main(int argc, char* argv[]){

printf("Hello World!\n");return 0;

}

It will compile, giving you

a good starting point for your

code. Remember to use

Build/Rebuild All

8

Advice for lab sessions

#include "stdafx.h"

int main(int argc, char* argv[]){

printf("Hello World!\n");return 0;

}

This is specific to the Microsoft

compiler - just leave it there and

everything should work properly

9

Advice for lab sessions

#include "stdafx.h"

int main(int argc, char* argv[]){

printf("Hello World!\n");return 0;

}

These are used

if you need to access any command

line parameters passed to the

program. Having them here

won’t do any harm, but you can delete

them if you like

10

Advice for lab sessions

#include "stdafx.h"

int main( ){

printf("Hello World!\n");return 0;

} You can get rid of the printf line

but you do need to keep the return 0; line

11

Advice for lab sessions

#include "stdafx.h"class creature{};

int main(){

return 0;}

Add your class definition as

a ‘skeleton’: add the opening

and closing braces and semicolon

and compile before adding

any more detail

12

Advice for lab sessions

#include "stdafx.h"class creature{private:

int yearOfBirth;public:

int getYearOfBirth();void setYearOfBirth(int YOB);

};

int main(){

printf("Hello World!\n");return 0;

}

Now you can start to

‘flesh out’ the class definition

13

Classes and objects recap

The creature class - analysis of the component parts (handout)

14

#include "stdafx.h"

#include <iostream.h>

class creature

{

private:

int yearOfBirth;

public:

creature();

virtual ~creature();

int getYearOfBirth();

void setYearOfBirth(int year);

};

int main()

{

creature myDog;

myDog.setYearOfBirth(1966);

cout << "my dog was born in" << myDog.getYearOfBirth() << endl;

return 0;

}

15

creature::creature()

{

cout << "constructor called for creature object." << endl;

}

creature::~creature()

{

cout << "destructor called for creature object." << endl;

}

void creature::setYearOfBirth(int year)

{

yearOfBirth = year;

}

int creature::getYearOfBirth()

{

return yearOfBirth;

}

16

Now for something new..

Inheritance

17

What is Inheritance?

Classes organised into a ‘classification hierarchy’

Classes can inherit attributes and methods from other classes

Inheriting class can add extra attributes and or methods of its own

18

What is the purpose of Inheritance?

SpecialisationExtending the functionality of an existing

classGeneralisation

sharing commonality between two or more classes

Improved efficiency and greater robustness Plays a major part in polymorphism

-more about this in two weeks time

19

Terminology

Derived class or subclass or child class. A class which inherits some of its attributes and

methods from another class Base class or superclass or parent class.

A class from which another class inherits ancestor.

A class’s ancestors are those from which its own superclasses inherit

descendant.A class’s descendants are those which inherit from its

subclasses

20

Terminology - a classification Hierarchy

Building

Commercial Public Domestic

Officeblock

Factory

Cathedral Hospital

Officeblock

ApartmentBlock

21

Terminology - a classification Hierarchy

Generalisation

Specialisation

Building

Commercial Public Domestic

Officeblock

Factory

Cathedral Hospital

Officeblock

ApartmentBlock

22

Terminology - a classification Hierarchy

Generalised

‘base class’Building

Commercial Public Domestic

Officeblock

Factory

Cathedral Hospital

Officeblock

ApartmentBlock

23

Terminology - a classification Hierarchy

Building

Commercial Public Domestic

Officeblock

Factory

Cathedral Hospital

Officeblock

ApartmentBlock

A ‘kind of’ Building

(AKO)

24

Terminology - a classification Hierarchy

Building

Commercial Public Domestic

Officeblock

Factory

Cathedral Hospital

Officeblock

ApartmentBlock

A ‘kind of’

Commercial building

(AKO)

25

Terminology - a classification Hierarchy

Building

Commercial Public Domestic

Officeblock

Factory

Cathedral Hospital

Officeblock

ApartmentBlock

Arrow in diagram

means

’inherits from’

26

Designing your classification hierarchy:‘A kind of’ or ‘a part of’?

Car

Vehicle

A car is ‘a kind of’ vehicle

car class can inherit from

vehicle class

27

Car

Car

Wheel

Vehicle

A car is ‘a kind of’ vehicle

car class can inherit from

vehicle class

A wheel isn’t ‘a kind of’ car.

A wheel is ‘a part of’ a car

- this is dealt with by aggregation

which is next week’s topic

Designing your classification hierarchy:‘A kind of’ or ‘a part of’?

28

Need to analyse whether differences between objects are dependant on type (such as a house being different to a factory) or state. (different values of the class’s attributes)

Building

Short Building

TallBuilding

short building and tall buildingmight vary only in the value of

the height attribute - don’t need separate classes

Designing your classification hierarchy:Different classes or different states?

29

What do objects inherit?

Line

Attributes:start positionend position

Methods:draw

Coloured Line

Attributes:colour

Methods:set colour

A ‘coloured line’ is a kind of linethe coloured line class inherits all

the attributes and methods ofthe line class and adds attributes

and methods of its own

An object of the ‘coloured line’class has all the attributes and

methods of the ‘line’ base class aswell as the attributes and methods

added by the derived class

30

Specialisation

Extending the functionality of an existing class

eg a coloured line is a specialised kind of line

31

Specialisation

A class is both closed in that it has an

encapsulated, private part which cannot be affected by external manipulation

and open in that it allows itself to be used as part of a larger software unit.

32

Generalisation

Sharing commonality between two or more classes

If we were modelling animals in a zoo would we create a separate class for each animal type?

This would duplicate attributes such as legs and methods such as getAge()

Cow Whale EagleElephant

33

Generalisation

Helpful to place common elements (attributes and methods) in a shared base class and organise problem into an inheritance hierarchy.

Cow Whale EagleElephant

Animal

Mammal Bird

34

Generalisation

Sometimes this leads to the creation of abstract classes which can’t be instantiated directly

Cow Whale EagleElephant

Animal

Mammal Bird

Abstract classes

35

Generalisation

concrete classes can be instantiated directly

Cow Whale EagleElephant

Animal

Mammal BirdConcrete classes

36

C++ Syntax

The colon (:) operator to denote inheritance

Public and private derivation of object methods from a base class

The ‘protected’ keyword to allow derived classes to access inherited attributes

37

C++ Syntax

class BaseClass{private:

int x;public:

void setX(int x_in); int getX();

}

A simple base classwith one private attribute x

and two public methods

38

C++ Syntax: public derivation

class DerivedClass: public BaseClass{private:

int y;public:

void setY(int y_in); int getY();

}

A derived class.The colon operator means

the derived classinherits from the base class

39

C++ Syntax: public derivation

class DerivedClass: public BaseClass{private:

int y;public:

void setY(int y_in); int getY();

}

the public derivation means that objects of the derived classcan access the public methodsand attributes of the base class

This is the most usual typeof derivation

40

C++ Syntax: public derivation

class BaseClass { private:

int x; public:

void setX(int x_in); int getX();

}

class DerivedClass: public BaseClass { private:

int y; public:

void setY(int y_in); int getY();

}

Main(){BaseClass base_object;DerivedClass derived_object;

base_object.setX(7);

derived_object.setX(12);derived_object.setY(1);

return 0;}

Object of the derivedclass can access methods

of the derived classand also methods of the

base class

41

C++ Syntax: private derivation

class DerivedClass: private BaseClass{private:

int y;public:

void setY(int y_in); int getY();

}

Another derived class - the privatederivation means that objects

of the derived class can’taccess the public methods and

attributes of the base class - butthe methods of the derived class

can!This is the least common type

42

C++ Syntax: the ‘protected’ keyword

An object of a publicly derived class can access the public methods of the base class, but not the private attributes

Changing the private keyword in the base class to protected makes the attributes available to derived classes

43

C++ Syntax: inheriting constructors

A derived class always inherits the constructor of the base class. The base class constructor is called first.

If the base class constructor takes no parameters then the inheritance is implicit - you don’t need to do anything!

If the base class constructor takes parameters then each derived class needs to declare a constructor with the same parameters. You can pass the arguments given to the derived class constructor to the constructor for the base class

44

C++ Syntax: inheriting constructors

class Customer{Customer (char * name_in);…}

Class AccountCustomer:public Customer{AccountCustomer(char * name_in);..}

Base class declares aconstructor that takes

a char pointer parameter

Derived class declares aconstructor that takes the

same char pointer parameter

45

C++ Syntax: inheriting constructors

AccountCustomer: AccountCustomer(char * name_in):

Customer (name_in){//main body of constructor..}

In the implementation of theconstructor for the derived class,

the parameter passed to thederived class constructor is

passed down to the base class constructor. Note use of the colon (:) syntax once again

46

C++ Syntax: inheriting constructors

class creature{private:

int yearOfBirth;public:

creature(int YOB);int getYearOfBirth();

};

int main(){

creature myCreature(1985);cout << "my creature was born in " << myCreature.getYearOfBirth() <<endl;return 0;

}

This class has a constructorthat takes an integer argument.

When instantiating an object ofthis class you pass a parameter

to the constructor.

47

C++ Syntax: inheriting constructors

class dog:public creature{public:

void bark();};

int main(){

creature myCreature(1985);dog myDog(1985);

cout << "my creature was born in " << myCreature.getYearOfBirth() <<endl;

return 0;}

At the moment we can’t do this:there is no constructor for thedog class that takes an integer

argument

Dog class derived fromcreature class

48

C++ Syntax: inheriting constructors

class dog:public creature{public:

dog(int YOB);void bark();

};

//implementation for dog constructordog::dog(int YOB):creature(YOB){//other constructor stuff goes here}

Now we have defined aconstructor that does take

an integer argument

The argument sent to thedog constructor gets sent

to the creature constructorso the YearOfBirth attributeof the base class gets set

properly

49

C++ Syntax: inheriting constructors

class dog:public creature{public:

dog(int YOB);void bark();

};

int main(){

creature myCreature(1985);dog myDog(1985);

cout << "my creature was born in " << myCreature.getYearOfBirth() <<endl;cout << "my dog was born in " << myDog.getYearOfBirth() <<endl;return 0;

}

Now we do have anappropriate constructorfor the dog class whichcorrectly initialises the

attributes defined in thebase class

50

C++ Syntax: inheriting destructors

A derived class always inherits the destructor of the base class. The derived class destructor is called first. This is the reverse of the sequence for constructors

Because destructors never take an argument there is no issue with inheritance of destructor parameters.

51

Summary: Inheritance

Inheritance allows classes to inherit attributes and methods from other classes in a classification hierarchy

Inheritance allows specialisation (extending the functionality of an existing class) and generalisation (sharing commonality between two or more classes)

Inheritance is appropriate where a class can be said to be ‘a kind of’ other class

52

Summary: Inheritance

Inheriting from a class doesn’t affect the integrity of that class - objects of the original base class can still be created

Generalisation allows removal of redundancy and duplication among classes

Some base classes are abstract - they are not specific enough to be instantiated but act as holders for common attributes and methods of derived classes

53

Summary: Inheritance

In C++ the protected keyword allows methods of a derived class access to its inherited attributes

Base class constructor methods are automatically called by the constructors of derived classes but argument lists must be compatible

Destructors are called in the reverse order of constructors