1 Object Oriented Programming Development - Week8 z Rob Manton z z Room D104.

Slides:



Advertisements
Similar presentations
1 Object Oriented Programming Development - Week 5 z By: Marc Conrad University of Luton z z Room: D104.
Advertisements

CPA: C++ Polymorphism Copyright © 2007 Mohamed Iqbal Pallipurath Overview of C++ Polymorphism Two main kinds of types in C++: native and user-defined –User-defined.
Dynamic Polymorphism Lecture-11. Method Polymorphism In a monomorphic language there is always a one to one relationship between a function name and it’s.
CSE 1302 Lecture 8 Inheritance Richard Gesick Figures from Deitel, “Visual C#”, Pearson.
Inheritance Definition Relationships Member Access Control Data Encapsulation Overloading vs. Overriding Constructors & Destructors.
Object Oriented Programming.  OOP Basic Principles  C++ Classes  September 2004  John Edgar 22.
Data Abstraction and Object- Oriented Programming CS351 – Programming Paradigms.
Chapter 10 Classes Continued
C++ fundamentals.
Virtual Functions Junaed Sattar November 10, 2008 Lecture 10.
Shallow Versus Deep Copy and Pointers Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data.
(c) University of Washington03-1 CSC 143 Java Inheritance Reading: Ch. 10.
1 Object Oriented Programming Development z By: Marc Conrad University of Luton z z Room: D104.
LECTURE 07 Programming using C# Inheritance
Association & Aggregation Lecture-9. Vehicle Car Tyre Engine Bus Passenger.
1 Object Oriented Programming Development - Polymorphism I z By: Marc Conrad & Rob Manton University of Luton z
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
CSE 333 – SECTION 4. Overview Pointers vs. references Const Classes, constructors, new, delete, etc. More operator overloading.
Pointer Data Type and Pointer Variables
Chapter 15 – Inheritance, Virtual Functions, and Polymorphism
Object Oriented Programming Development
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
Polymorphism. Introduction ‘one name multiple forms’ Implemented using overloaded functions and operators Early binding or static binding or static linking.
Overview of Previous Lesson(s) Over View  OOP  A class is a data type that you define to suit customized application requirements.  A class can be.
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
1 What is Inheritance? zThe mechanism of deriving a new class from an old one is called inheritance zClasses organised into a ‘classification hierarchy’
Lecture 8 Inheritance Richard Gesick. 2 OBJECTIVES How inheritance promotes software reusability. The concepts of base classes and derived classes. To.
Inheritance. Recall the plant that we defined earlier… class Plant { public: Plant( double theHeight ) : hasLeaves( true ), height (theHeight) { } Plant(
1 Object Oriented Programming Development - Week 4 z By: Rob Manton University of Luton z z Room: D104.
Objects Mark Hennessy Dept. Computer Science NUI Maynooth C++ Workshop 18 th – 22 nd September 2006.
Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Unit IV Unit IV: Virtual functions concepts, Abstracts classes & pure virtual functions. Virtual base classes, Friend functions, Static functions, Assignment.
1 Practical test tomorrow zWill involve writing a simple class zinstantiating objects zother C++ constructs as practised in the lab sheets to date zinheritance.
Inheritence Mark Hennessy Dept. Computer Science NUI Maynooth C++ Workshop 18 th – 22 nd September.
1 Object Oriented Programming Development - Multi File Development z By: Marc Conrad & Rob Manton University of Luton z
Programming Languages by Ravi Sethi Chapter 6: Groupings of Data and Operations.
1 Object Oriented Programming Development - Week7 z Rob Manton z z Room D104.
1 Inheritance. 2 Why use inheritance?  The most important aspect of inheritance is that it expresses a relationship between the new class and the base.
1 Object Oriented Programming Development - Week 3 z By: Marc Conrad University of Luton z z Room: D104.
Object-Oriented Programming in C++
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes.
1 What is the purpose of Inheritance? zSpecialisation Extending the functionality of an existing class zGeneralisation sharing commonality between two.
Programming in Java CSCI-2220 Object Oriented Programming.
Object-Oriented Programming in C++ More examples of Association.
More C++ Features True object initialisation
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Simple Classes. ADTs A specification for a real world data item –defines types and valid ranges –defines valid operations on the data. Specification is.
1 CSC241: Object Oriented Programming Lecture No 02.
OOP in C++ CS 124. Program Structure C++ Program: collection of files Source (.cpp) files be compiled separately to be linked into an executable Files.
Coming up: Inheritance
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Overview of C++ Polymorphism
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Monday, Jan 27, 2003Kate Gregory with material from Deitel and Deitel Week 4 Questions from Last Week Hand in Lab 2 Classes.
Dynamic Memory Management & Static Class Members Lecture No 7 Object Oriented Programming COMSATS Institute of Information Technology.
Chapter 12: Pointers, Classes, Virtual Functions, Abstract Classes, and Lists.
MAITRAYEE MUKERJI Object Oriented Programming in C++: Hierarchy / Inheritance.
Object Lifetimes and Dynamic Objects Lecture-7. Object Lifetimes and Dynamic Objects External (Global) Objects Persistent (in existence) throughout the.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Inheritance & Classification Hierarchies Lecture-8.
Inheritance & Polymorphism
Review: Two Programming Paradigms
Object Lifetime and Dynamic Objects
Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
CISC/CMPE320 - Prof. McLeod
Overview of C++ Polymorphism
Presentation transcript:

1 Object Oriented Programming Development - Week8 z Rob Manton z z Room D104

2 Module Outline zIntroduction zNon object oriented basics zClasses z Inheritance z Aggregation z Polymorphism z Multifile Development

3 Today: zSome advice for next week’s test zInheritance recap zAggregation

4 Practical Test in Week 9 Tuesday 26th November in two sittings 5-6pm and pm zWill involve writing a simple class zinstantiating objects zother C++ constructs as practised in the lab sheets to date zinheritance and or aggregation

5 Last week: Inheritance zInheritance allows classes to inherit attributes and methods from other classes in a classification hierarchy

6 Last week: Inheritance Inheritance allows zspecialisation (extending the functionality of an existing class) zgeneralisation (sharing commonality between two or more classes)

7 Last week: Inheritance zInheritance is appropriate where a class can be said to be ‘a kind of’ other class Car Vehicle A car is ‘a kind of’ vehicle car class can inherit from vehicle class

8 Last week: Inheritance zInheritance is appropriate where a class can be said to be ‘a kind of’ other class Car Wheel  A wheel isn’t ‘a kind of’ car. A wheel is ‘a part of’ a car - this is dealt with by aggregation which is this week’s topic

9 Last week: Inheritance zInheriting from a class doesn’t affect the integrity of that class - objects of the original base class can still be created zGeneralisation allows removal of redundancy and duplication among classes zSome base classes are abstract - they are not specific enough to be instantiated but act as holders for common attributes and methods of derived classes

10 Last week: C++ Syntax zThe colon (:) operator to denote inheritance zPublic and private derivation of object methods from a base class zThe ‘protected’ keyword to allow derived classes to access inherited attributes

11 C++ Syntax: public derivation zClass DerivedClass: public BaseClass z{ zprivate: yint y; zpublic: yvoid setY(int y_in); yint getY(); z} A derived class. The colon operator means the derived class inherits from the base class

12 C++ Syntax: public derivation zClass DerivedClass: public BaseClass z{ zprivate: yint y; zpublic: yvoid setY(int y_in); yint getY(); z} the public derivation means that objects of the derived class can access the public methods and attributes of the base class This is the most usual type of derivation

13 C++ Syntax: public derivation zclass BaseClass z{ zprivate: yint x; zpublic: yvoid setX(int x_in); yint getX(); z}; zclass DerivedClass: public BaseClass z{ zprivate: yint y; zpublic: yvoid setY(int y_in); yint getY(); z}; Main() { BaseClass base_object; DerivedClass derived_object; base_object.setX(7); derived_object.setX(12); derived_object.setY(1); return 0; } Object of the derived class can access methods of the derived class and also methods of the base class

14 C++ Syntax: public derivation Publicly derived class objects of this class are able to call public methods of the base class Public derivation is the most common type

15 C++ Syntax: private derivation Changed to a Privately derived class objects of this class are NOT able to call public methods of the base class - this won’t compile!

16 Last week: public/private inheritance zPublic inheritance allows all public methods of ancestor classes to be available to objects of a derived class Line Attributes: start position end position Methods: draw Coloured Line Attributes: colour Methods: setColour Class ColouredLine: public Line { …. }; main() { ColouredLine myLine; myLine.draw(); } Object of derived class can access method of base class

17 Last week: public/private inheritance zPrivate inheritance prevents objects of the derived class from calling the public methods of the ancestor class Line Attributes: start position end position Methods: draw Coloured Line Attributes: colour Methods: setColour Class ColouredLine: private Line { …. }; main() { ColouredLine myLine; // myLine.draw(); } Object of privately derived class can’t access method of base class 

18 private/public/protected attributes zNow a quick comparison between public, private and protected attributes..

19 C++ Syntax: private attributes We have a privately defined attribute x in the base class

20 C++ Syntax: private attributes Here we have a method in the derived class (getIfYEqX) that needs to access an attribute (x) declared in the base class

21 C++ Syntax: private attributes Because ‘x’ is declared as private in the base class, the derived class is not allowed to access it directly so we get an error and the code won’t compile

22 C++ Syntax: public attributes If we change the attribute to be public then the method in the derived class can access it but...

23 C++ Syntax: public attributes Doing this goes against the idea of encapsulation and data hiding users of the class can access the attributes directly which is a bad idea usually!

24 C++ Syntax: protected attributes If we change the attribute to be protected then the method in the derived class can access the attribute in the base class..

25 C++ Syntax: protected attributes And the notion of encapsulation and data hiding is preserved because users of the class aren’t allowed to access the protected attribute directly

26 C++ Syntax: the ‘protected’ keyword So in summary...Protected attributes share some features of public and some of private: zDerived classes can access the protected attributes of their ancestor classes (as if they were publicly defined) zbut external users of the class can’t access the protected attributes (as if they were privately defined)

27 C++ Syntax: inheriting constructors zA derived class always inherits the constructor of the base class. The base class constructor is called first. zIf the base class constructor takes no parameters then the inheritance is implicit - you don’t need to do anything! zIf 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

28 C++ Syntax: inheriting constructors Class Customer { Customer (char * name_in); … } Class AccountCustomer:public Customer { AccountCustomer(char * name_in);.. } Base class declares a constructor that takes a char pointer parameter Derived class declares a constructor that takes the same char pointer parameter

29 C++ Syntax: inheriting constructors AccountCustomer: AccountCustomer(char * name_in): Customer (name_in) { //main body of constructor.. } In the implementation of the constructor for the derived class, the parameter passed to the derived class constructor is passed down to the base class constructor. Note use of the colon (:) syntax once again

30 C++ Syntax: inheriting constructors class creature { private: int yearOfBirth; public: creature(int YOB); intgetYearOfBirth(); }; int main() { creature myCreature(1985); cout << "my creature was born in " << myCreature.getYearOfBirth() <<endl; return 0; } This class has a constructor that takes an integer argument. When instantiating an object of this class you pass a parameter to the constructor.

31 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 the dog class that takes an integer argument Dog class derived from creature class

32 C++ Syntax: inheriting constructors class dog:public creature { public: dog(int YOB); void bark(); }; //implementation for dog constructor dog::dog(int YOB): creature(YOB) { //other constructor stuff goes here } Now we have defined a constructor that does take an integer argument The argument sent to the dog constructor gets sent to the creature constructor so the YearOfBirth attribute of the base class gets set properly

33 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 an appropriate constructor for the dog class which correctly initialises the attributes defined in the base class

34 C++ Syntax: inheriting destructors zA 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 zBecause destructors never take an argument there is no issue with inheritance of destructor parameters.

35 This week’s new topic zAssociations links between objects zAggregations objects composed wholly or partly of others

36 Associations zUp to now we have made single objects and called their methods from the main() function. zIn practice it is likely that we will have many objects that will need to communicate with each other..

37 Types of associations Associations can take many forms yone to one yone to many ymany to many ybidirectional yunidirectional

38 Types of associations Associations can take many forms yone to one one object of a class has a link to one other object of a class yone to many ymany to many ybidirectional yunidirectional

39 Types of associations Associations can take many forms yone to one yone to many one object of a class has many links with objects of a particular class ymany to many ybidirectional yunidirectional

40 Types of associations Associations can take many forms yone to one yone to many ymany to many many objects of one class have links with many objects of a particular class ybidirectional yunidirectional

41 Types of associations Associations can take many forms yone to one yone to many ymany to many ybidirectional messages can be sent in both directions yunidirectional

42 Types of associations Associations can take many forms yone to one yone to many ymany to many ybidirectional yunidirectional messages only need to be sent in one direction. One object is the ‘actor’ - acts upon another the other is a server - it is only acted upon. [Booch,1994]

43 Aggregation zAggregations Up to now we have made classes that use simple data types for their attributes - (int, float, char etc) Aggregations use objects of other classes to define their state

44 Terms used to describe aggregation yAggregation yComposition yPart-Whole yA part of (APO) yHas-a yContainment

45 Aggregation yAggregation

46 Composition vs Aggregation yComposition Implies that the internal objects are not seen from the outside. yAggregation implies that some objects have some visibility or existence outside of the hierarchy

47 Containment yContainment a composition hierarchy defines how an object is composed of other objects in a fixed relationship. Aggregate object cannot exist without its components. Eg a car and its engine have a containment relationship yA Container an object of a container class which is able to contain other objects. Its existence is independent of whether it actually contains anything. Contained objects will probably be dynamic and vary over time. Eg a car boot is a container which is able to contain some or no objects

48 Aggregations Aggregations can be yfixed - like in composition - the number and identity of contained objects is always the same yvariable - as with a container object - the number of contained objects may vary at runtime yrecursive may contain components of its own type

49 Fixed Aggregation in C++ Fixed aggregation - declare attributes as objects rather than standard data types class car { private: engine myEngine; light left_headlight; light right_headlight; }; Class attributes now include objects of other classes

50 Fixed Aggregation in C++ aggregated class can then call methods of the component objects void car::LightsOn() { left_headlight.switchOn(); right_headlight.switchOn(); } Car class methods can now call methods of the contained objects

51 Fixed Aggregation with parameters What if the contained objects require parameters for their construction? class wheel { private: int diameter; public: wheel(diameter_in); int getDiameter(); }; Constructor for wheel class takes an integer argument to define its diameter

52 Fixed Aggregation with parameters What if the contained objects require parameters for their construction? class car { private: wheel l_front, r_front, l_back, r_back; engine theEngine; public: car (int diameter_in,int enginecc_in); }; Constructor for car class takes enough parameters to construct all the constituent objects

53 Fixed Aggregation with parameters What if the contained objects require parameters for their construction? car::car (int diameter_in,int enginecc_in): l_front(diameter_in), r_front(diameter_in), l_back(diameter_in), r_back(diameter_in), theEngine(enginecc_in) { //rest of constructor code goes here } Note use of colon(:) operator to pass parameters sent to constructor of aggregated object to the constructors of the constituent objects

54 Variable Aggregation in C++ Variable aggregation - declare attributes as object pointers rather than standard data types. Pointers can be set to NULL to represent no object class car { private: person * theDriver = NULL;..};

55 Variable Aggregation in C++ Variable aggregation - declare attributes as object pointers rather than standard data types. Pointers can be set to NULL to represent no object class car { private: person * theDriver = NULL;..}; Class attributes now include pointers to objects of other classes

56 Variable Aggregation in C++ car::addDriver() { theDriver=new person(); } We could have a method which instantiates an object of the contained class and allocates it to the pointer like this..

57 Variable Aggregation in C++ car::addDriver() { theDriver=new person(); } car::removeDriver() { delete the Driver; theDriver=NULL; }..and deletes it like this

58 Variable Aggregation in C++ However, some objects in an aggregation may have a lifetime outside of the contained object. In this case a pointer to the previously existing object needs to be passed to the containing object car::addDriver(person * driver_in) { theDriver=driver_in; }

59 Variable Aggregation in C++ However, some objects in an aggregation may have a lifetime outside of the contained object. In this case a pointer to the previously existing object needs to be passed to the containing object car::addDriver(person * driver_in) { theDriver=driver_in; } A pointer to a previously existing object is now available to the aggregated object

60 Variable Aggregation in C++ Removing the object from the aggregation simply means setting the pointer to null. (the object continues to exist in its own right but not as part of the aggregation) car::removeDriver() { theDriver=NULL; }

61 Variable Aggregation in C++ Removing the object from the aggregation simply means setting the pointer to null. (the object continues to exist in its own right but not as part of the aggregation) car::removeDriver() { theDriver=NULL; } The car object would now have no driver pointer but the driver person object would continue to exist outside of the car

62 Implementing associations in C++ forms of Associations yone to one yone to many ymany to many ybidirectional yunidirectional

63 Implementing associations in C++ forms of Associations yone to one unidirectional eg a light switch and a light the switch is an ‘actor’ - it acts upon another object [Brooch] the light is a server -it is told what to do switch needs a pointer to the light object to be able to control it

64 Implementing associations in C++ forms of Associations yone to one unidirectional main() { light * bigLight= new light(); button * lightButton=new button(bigLight);..} Create a dynamic light object pass its pointer to the constructor for the new button object button object can now call methods of the light object

65 Implementing associations in C++ forms of Associations yone to one bidirectional eg between two people objects who become ‘married’ two person objects of the same class each object needs a pointer to the other object (its ‘partner’)

66 Implementing associations in C++ forms of Associations yone to one bidirectional class person { private: person * partner;..} The person class now contains a pointer to another object of the person class. Initially this will be set to NULL, but when the person gets ‘married’ the partner pointer will point to another object of the person class

67 Implementing associations in C++ forms of Associations yone to one bidirectional main() { person * Fred=new person(); person * Wilma=new person(); Fred.marry(Wilma); Wilma.marry(Fred);..}

68 Implementing associations in C++ forms of Associations yone to one bidirectional main() { person * Fred=new person(); person * Wilma=new person(); Fred.marry(Wilma); Wilma.marry(Fred);..} We can create two dynamic person objects and then call the ‘marry’ method from each. This repetition is necessary to ensure both partners know who they are married to!

69 Implementing associations in C++ forms of Associations yone to one bidirectional a method of establishing both ends of the bidirectional link simultaneously is to use the this keyword All objects in C++ have a this pointer which points to themselves

70 Implementing associations in C++ forms of Associations yone to one bidirectional person::marry(person * partner_in) { //establish one way link partner=partner_in; //now do the other way partner->marry(this);..} When the ‘marry’ method of one object is called it automatically calls the ‘marry’ method of its new spouse!

71 Implementing associations in C++ Need to avoid an infinite recursive call here!

72 Implementing associations in C++ forms of Associations ymultiple associations Maintain an array of pointers and an integer attribute to record the current number of objects referenced. Car::addPassenger(person * passenger_in) { if (numPassengers<5) { passenger[numPassengers++]=passenger_in;

73 Implementing associations in C++ forms of Associations ymultiple associations Maintain an array of pointers and an integer attribute to record the current number of objects referenced. car::addPassenger(person * passenger_in) { if (numPassengers<5) { passenger[numPassengers++]=passenger_in; }..} numPassengers is an integer attribute of the car class If the car is not full then add the new passenger

74 Implementing associations in C++ forms of Associations ymultiple associations Maintain an array of pointers and an integer attribute to record the current number of objects referenced. car::addPassenger(person * passenger_in) { if (numPassengers<5) { passenger[numPassengers++]=passenger_in; }..} Here we use the postfix increment operator to update the numPassengers variable

75 Summary zAssociations links between objects zAggregations objects composed wholly or partly of others

76 Summary: associations forms of Associations yone to one yone to many ymany to many ybidirectional yunidirectional

77 Summary: Aggregation yComposition Implies that the internal objects are not seen from the outside. yAggregation implies that some objects have some visibility or existence outside of the hierarchy

78 Summary: Aggregation Aggregations can be yfixed - like in composition - the number and identity of contained objects is always the same - use named automatic objects yvariable - as with a container object - the number of contained objects may vary at runtime - use pointers which can be NULL yrecursive may contain components of its own type