Presentation is loading. Please wait.

Presentation is loading. Please wait.

Inheritance and Aggregation Lecture - 8. 2 References Inheritance from Lecture Notes on Object Oriented Programming with C++. Available at

Similar presentations


Presentation on theme: "Inheritance and Aggregation Lecture - 8. 2 References Inheritance from Lecture Notes on Object Oriented Programming with C++. Available at"— Presentation transcript:

1 Inheritance and Aggregation Lecture - 8

2 2 References Inheritance from Lecture Notes on Object Oriented Programming with C++. Available at http://www.geocities.com/obashir/interests/cpp/ LECT08.DOC. Aggregation Lecture Notes on Object Oriented Programming with C++. Available at http://www.geocities.com/obashir/interests/cpp/ LECT9.DOC.

3 3 Inheritance Mechanism to allow organization of classes into a classification hierarchy. This classification hierarchy allows classes to inherit attributes and methods from other classes. The inheriting class can add extra attributes and methods of its own.

4 4 Inheritance TerminologyDescription Derived Class Sub Class Child Class A class which inherits some of its attributes and methods from another class. Base Class Super Class Parent Class A class from which another class inherits. AncestorsA class’s ancestors are those from which its own super class inherits. DescendantsA class’s descendants are those which inherit from its subclass

5 5 Inheritance Complementary roles of inheritance –Specialization i.e. extending the functionality of an existing class. –Generalization i.e. sharing commonality between multiple classes. Specialization and generalization are not mutually exclusive and might be regarded top down and bottom up approaches, respectively, to the same structure.

6 6 Inheritance Top down approach –Specialized classes are derived from a common base class. Bottom up approach –Separate similar classes are generalized into a common base class. Practically the two approaches tend to be part of the same iterative process of analysis and design. Top down specialization approach is more closely associated with the reuse of existing classes.

7 7 Classification Hierarchy Product of inheritance. Defines a relationship between classes whereby one class is considered to be a kind of another class. As the hierarchy is traversed from top to bottom more specialized classes are encountered/created by introducing more functionality.

8 8 Classification Hierarchy (Contd…)

9 9 Difference between a kind of and a part of Relationship Examples –Jet Engine is a kind of Engine. –Compressor is a part of a Jet Engine. is a part of relationship is also known as Aggregation.

10 10 Different Classes or Different States and Attributes When designing a class hierarchy, differentiate between objects that need to represented by different classes and those belonging to same class but having different states and attributes. This requires analysis of differences between objects as being a difference in type or a difference in state or attribute.

11 11 Different Classes or Different States and Attributes (Contd…) Creating a classification actually relating to a state or an attribute common to all objects of the parent class is not appropriate.

12 12 What is inherited ? Inheritance mechanism exist between classes and not objects. A class does not contain any attribute or state value. Attribute and state values are contained in individual objects. Classes only are a blueprint to define the variables each object of a class should have.

13 13 What is inherited ? (Contd…) A derived class automatically contains all attributes and methods of the base class. A derived class is by default identical to the base class but it can be extended and defined. Objects of the derived class do not inherit anything from objects of the base class.

14 14 What is inherited ? (Contd…)

15 15 Specialization – Extending Functionality Allow reuse of existing software classes to extend their behavior. This allows requirements for specific specialized classes to be met without affecting original classes. Third party software components can be extended to fulfill specific requirements.

16 16 Generalization – Sharing Commonality When some common attributes and associated methods are detected while analyzing particular application objects, their classes can be arranged in a generalization hierarchy. Generalization allows the sharing of common elements between classes without having to repeat their definition for each separate class.

17 17 Abstract Base Classes Abstract base classes are not completely implemented. –The class has the interfaces specified but their functionality is not implemented. –Abstract classes may not be used to instantiate objects. Some of the base classes in a hierarchy do not represent anything concrete enough to be instantiated as objects. –Such classes only exist as holders for the shared (inherited) data and methods for the derived classes.

18 18 Abstract Base Classes (Contd…) –Known as abstract classes as they do not represent concrete types of objects. In the previous example –Vehicle does not in itself represent anything other than a generalization defining the shared characteristics of other classes. –Such classes cannot be used effectively to instantiate objects without the further detail provided by the specialized derived class types, e.g., car, truck, etc.

19 19 Accessing the Inherited Members A derived class can use the public members of the base class. Access to the private members of the base class is restricted even for the derived class. Members that need to be accessed by the derived class but not to be accessed by other objects are to be declared as protected, i.e., –Protected section of any class A is treated exactly like the private section of class A to code outside it. –Protected section of any class A is accessible to class B derived from class A.

20 20 Disadvantages of Protected Members Simply by inheriting from a library, a programmer has direct access to protected members of the base class. This makes protected sections of a class considerably less secure than its private members. To avoid unintended changes to data in the base class, it is often safer to force the derived classes to access and modify data in the base class using only the public methods.

21 21 Example: Alarm Clock a-kind-off Clock class AlarmClock:public Clock { private: TimeStructure tAlarmTime; int bAlarmSet; int bAlarmRinging; unsigned short uwAlarmRingCount; char aszTime[TIME_STRING_LENGTH]; public: AlarmClock(TimeStructure* ptSetTimeData):Clock(ptSetTimeData) { memset(&tAlarmTime,0,sizeof(TimeStructure)); bAlarmSet = 0; bAlarmRinging = 0; uwAlarmRingCount = 0; }

22 22 AlarmClock(TimeStructure* ptSetTimeData, TimeStructure* ptSetAlarmTime, int bInAlarmSet):Clock(ptSetTimeData) { tAlarmTime = *ptSetAlarmTime; bAlarmSet = bInAlarmSet; bAlarmRinging = 0; uwAlarmRingCount = 0; } void GetAlarmTime(TimeStructure* ptGetAlarmTimeData); void SetAlarm(void); void ResetAlarm(void); char* toString(void); void tick(void); }; Example: Alarm Clock a-kind-off Clock (Contd.)

23 23 Example: Execution

24 24 Example: Execution (Contd.)

25 25 Inheritance Diagrams

26 26 Aggregation and Composition Aggregation is a relationship between objects that can be defined by a number of similar terms, i.e., –Composition, –Part-Whole, –A-Part-Of, –Has-A, –Containment

27 27 Aggregation and Composition (Contd…) In aggregation, an object of the enclosing class is wholly or partially composed of objects of other classes. In composition relationship, classes do not inherit from other classes. An object of one class may have its representation defined by other objects rather than by variables and data structures.

28 28 Containment Vs Containers Container classes may contain objects of other classes but do not depend upon them for their representation. In containment a composition relationship defines how an object is composed of other objects in a fixed relationship. Aggregated objects cannot exist without its component which will probably be of a fixed and stable number or at least will vary within a fixed set of possibilities.

29 29 Containment Vs Containers (Contd…) A container is an object that is able to contain other objects without depending upon them for its functionality. Therefore, the existence of a container is independent of whether it actually contains any object at a particular instant. Objects in a container are probably dynamic and possibly form a heterogeneous collection (i.e., the objects contained may be of many different classes)

30 30 Containment Vs Containers (Contd…) Examples –An engine is-a-part of car –Storage compartment of a car can contain boxes. –The integrity of a car as an object is not affected by what is in the storage compartment. –Storage compartment is simply a container and exists independently of its contents. –Objects contained within the storage compartment do not affect the behavior of the car object. Containers commonly used in computing, –Stacks –Queues –Trees

31 31 Aggregation and Abstraction In a composition relationship, the composite object is more abstract than the component objects. Unlike a classification hierarchy, elements of a composition relationship must represent instantiated objects at runtime. –If class Aeroplane is derived from a base class Vehicle, to instantiate an object of Aeroplane, an object of Vehicle need not be instantiated. –If class Aeroplane contains two objects of class JetEngine, an instantiation of Aeroplane cannot exists without two instances of JetEngine.

32 32 Aggregation and Abstraction (Contd.) Aggregation in object orientation is a partial application of aggregation. –Composite objects consist of not only component objects but also other attribute and state variables that are not objects of any class. –Often component objects are artifacts of implementation being programming tools rather than representing real world entities. –Thus aggregation in software is very different from pure hardware aggregation of parts.

33 33 Properties of Aggregation Transivity –If Engine is a part of Car and Radiator is a part of Engine, then Radiator is also a part of Car. Antisymmetry –If Engine is a part of Car then Car cannot be a part of Engine. Propagation –Environment of parts is the same as that of the assembly. –If Car is in the Garage then Engine is unlikely to be elsewhere.

34 34 Layered Aggregation Aggregation may exist in several layers. –Objects may be composed of other objects which in turn may be composed for further objects. Objects that are parts of larger objects may or may not have an existence independent of the larger object. Aggregations with strong ownership and coincident lifetime constraints are usually referred to as composition. –Composites tightly contain components. –Components live and die with composites.

35 35 Types of Aggregation Fixed Aggregation –Particular number and types of component parts are predefined. Variable Aggregation –Number of levels of aggregation are fixed but the number of parts vary. Recursive Aggregation –An object contains components of its own type.

36 36 Delegation Use of objects as implementation components for other objects involving use of only part of their interfaces. Components in a delegation relationship are not fully utilised by the composite object because only a part of its behaviour might be appropriate in a particular context. Considered useful in situations where inheritance may be considered appropriate but the inheritance of the entire behaviour of a class is not required.

37 37 Delegation: an Alternative of Inheritance Delegation appropriate in situations where the base class contains methods inappropriate for the new class. –New class is not truly a kind of the existing base class but merely similar to the base class. Containment of the object in delegation is thus used to mask any behaviour that is not required.

38 38 Designing Classes using Aggregation Inheritance is restrictive as it results in a fixed relationship between classes. This restricts the use of classes in a hierarchy in applications other than for which inheritance is employed. Open systems based on code reusability beyond a class library are based on a layered approach. Objects at each level are constructed from aggregation of objects at the lower levels. –Preferably the level immediately below.

39 39 Aggregation Based Layered Model Application Layer Semantic Binding Layer Primitive Application Layer System Interface Layer Built-in Data Types Collection Classes Object Services

40 40 Aggregation Based Layered Model (Contd.) Built in Data Types –This level needs to be encapsulated. –Machine representation level. –Data types vary significantly between platforms and operating systems. System Interface Layer –Simple data types encapsulated as classes to make them open. –Environment specific representation of standard data types is hidden behind the interface of objects.

41 41 Primitive Application Layer –Objects appropriate in scale to be attributes of application classes may be modeled here. –Affords opportunity to add methods implementing appropriate behaviour rather than leaving this responsibility to the encapsulating classes. –e.g., for a banking application, classes at this level are Client name, Account number –These classes are composed of types defined in the system interface layer. Aggregation Based Layered Model (Contd.)

42 42 Semantic Binding Layer –Attribute objects are aggregated into classes appropriate for application sized objects. –e.g., Customer details, Bank account. –These objects are composed of primitive application layer objects. Application Layer –Large scale objects that are instantiated in the final application. Aggregation Based Layered Model (Contd.)

43 43 Example: Calculator class Calculator { private: Console UserInterface; Processor Cray; public: void operate(void); };

44 44 Processor: A Calculator Component class Processor { private: float LastAnswer; public: Processor(void); float Sum(float a,float b); float Subtract(float a,float b); float Multiply(float a,float b); float GetLastAnswer(void) int Divide(float a,float b, float *c); };

45 45 Console: A Calculator Component class Console { private: public: float GetOperand(char* Message); char GetOperator(void); void PrintAnswer(float Num); void PrintMessage(char* Message); };

46 46 Calculator::operate(void) void Calculator::operate(void) { char Option; float a,b,c; do { Option = UserInterface.GetOperator(); switch(Option) { case '+': a = UserInterface.GetOperand("Get operand 1 "); b = UserInterface.GetOperand("Get operand 2 "); c = Cray.Sum(a,b); UserInterface.PrintAnswer(c); break; case '-': a = UserInterface.GetOperand("Get operand 1 "); b = UserInterface.GetOperand("Get operand 2 "); c = Cray.Subtract(a,b); UserInterface.PrintAnswer(c); break;

47 47 Calculator::operate(void) case '*': a = UserInterface.GetOperand("Get operand 1 "); b = UserInterface.GetOperand("Get operand 2 "); c = Cray.Multiply(a,b); UserInterface.PrintAnswer(c); break; case '/': a = UserInterface.GetOperand("Get operand 1 "); b = UserInterface.GetOperand("Get operand 2 "); if (Cray.Divide(a,b,&c)) { UserInterface.PrintAnswer(c); } else { UserInterface.PrintMessage("Divide by zero..."); } break; } while (Option != 'e'); }

48 48 Calculator Application #include "aggregation.h" int main(void) { Calculator Casio; Casio.operate(); return(0); }

49 49 Example Session

50 50 Notations Calculator +operate():void Console +GetOperand(in Message: char*): float +GetOperator(): char +PrintAnswer(in Num: float):void +PrintMessage(in Message: char*):void Processor -LastAnswer:float +Processor() +Sum(in a: float, in b: float):float +Subtract(in a:float, in b:float):float +Multiply(in a:float, in b: float):float +GetLastAnswer():float +Divide(in a: float, in b: float, out c: float *):int 1 1 1 1

51 51 Notations A filled diamond attached to Calculator class on the association between Calculator class and Processor class indicates that –A calculator consists of a processor. –If a calculator is removed so is the processor associated with it. The filled diamond indicates composition. A hollow diamond would indicate aggregation. The numbers shown on each end of the association indicate multiplicity of the Processor class with the Calculator class. –Multiplicity specifies how many objects of a class are associated with a single object of the other class in an association.


Download ppt "Inheritance and Aggregation Lecture - 8. 2 References Inheritance from Lecture Notes on Object Oriented Programming with C++. Available at"

Similar presentations


Ads by Google