Presentation is loading. Please wait.

Presentation is loading. Please wait.

DCS 5085 Class Hierarchy Chapter 3. Overview Inheritance Why Inheritance Forms of Inheritance Advantages and Disadvantages Inheritance vs. Composition.

Similar presentations


Presentation on theme: "DCS 5085 Class Hierarchy Chapter 3. Overview Inheritance Why Inheritance Forms of Inheritance Advantages and Disadvantages Inheritance vs. Composition."— Presentation transcript:

1 DCS 5085 Class Hierarchy Chapter 3

2 Overview Inheritance Why Inheritance Forms of Inheritance Advantages and Disadvantages Inheritance vs. Composition

3 3.1 Inheritance In object oriented programming languages, classes can be organized into a hierarchical structure based on the concept of inheritance. Inheritance is the property by which instances of a child class (or subclass) can access attributes (both data and methods) associated with a parent class (or superclass). Inheritance is transitive, so that a child class can inherit features from superclasses many levels away. –I.e. if class ‘Cat’ is a subclass of ‘Mammal’ and class ‘Mammal’ is a subclass of ‘Animal’, then ‘Cat’ will inherit attributes both from ‘Mammal’ and from ‘Animal’. In general, inheritance is a mechanism of sharing commonalities between classes.

4 When a subclass inherits commonalities from two or more superclasses, this is termed multiple inheritance. When a subclass can inherit the properties and behavior of only one superclass, it is called single inheritance. C++ supports multiple inheritance, but Java does not. Shapes Quadrangle Rectangle Circle Oval Square Polygon Triangle Hierarchy representing inheritance

5 When new classes are constructed from existing classes using inheritance, an important aspect concerning the objects of the subclass is stated by the substitution rule of inheritance: Substitution Rule –Any object of the subclass must possess all data fields associated with the parent class, and must be usable in place of a superclass object. With reference to the previous figure, a ‘Square’ object can also act as a ‘Rectangle’ object or a ‘Polygon’ object. It may be noted that there may be violations of the above rule in certain forms of inheritance.

6 3.2 Why Inheritance There are times when we have a set of related classes for which we would like to share common code. Suppose we have a Circle class and a Rectangle class. There are certain attributes which are common to circles and rectangles, such as they both might have a point which represents the location of their center, and they both might have a color. However, the dimensions of a circle would probably be defined with a radius, while the dimensions of a rectangle might be defined with a length and width.

7 Conceptually, the objects might look something like this: Notice how we can arrange the members in the class so that the common elements are in the same location. We could then take the common elements from the Circle and Rectangle classes and build a common base class, which we could call Shape. We would then have the Circle and Rectangle classes extend the Shape class. Any code dealing with the common elements of the two shapes would only have to be defined once in the Shape class. Center Color Radius Width Length Color Center CircleRectangle

8 3.3 Forms of Inheritance Inheritance is used in a variety of ways, which can be broadly classified into the following: Inheritance for specialization: –This is the most common form of inheritance, in which the subclass is a specialized variety of the parent class, and satisfies all the specifications of the parent class. Inheritance for specification: –The parent class defines the behavior that is to be implemented in the child class. This form is different from the previous, in that the subclass is not a refinement of the existing parent class, but a realization of the incomplete specification of the parent class.

9 Inheritance for construction: –The purpose of this type of inheritance is to make use of some of the methods provided by the parent class. There may not be significant logical relationship between the subclass and the superclass. –This form of construction violates the substitution rule mentioned earlier. Inheritance for extension: –The child class adds only new behavior to the parent class, and does not modify or alter any of the inherited attributes. Inheritance for limitation: –The behavior of the subclass is more restrictive than the behavior of the superclass.

10 3.4 Advantages and Disadvantages Advantages: –Code Reusability Behavior of subclass does not have to rewritten. Reduces the costs of maintenance of shared components. Disadvantages: –Overuse of inheritance in a software can make it more complex. Multiple inheritance can create ambiguity between attributes and operations, and can increase the likelihood of errors.

11 Advantages and Disadvantages –Inheritance increases dependencies between a superclass and its subclasses. Modifications inside a superclass within a class hierarchy affect all subclasses. –Inheritance can also cause violation of encapsulation. Subclass can define new values for the inherited data of the parent class; it can also override methods in the original class by simply defining new methods with the same names as those of methods that appear in the parent class.

12 3.5 Inheritance vs. Composition Inheritance: –is-a rule when the first is a specialized version of the second, and inheritance can be applied to create the first as a subclass of the second. Examples are “Square is a Rectangle” (i.e, square can be a subclass of rectangle), “Cat is a Mammal”, “Stack is a List”. Composition: –Related technique for software reuse. –has-a rule when the second concept is a component of the first but the two are not in any sense the same thing. Example: Car has a Tyre, House has a Window, Menu has a Button.

13 Inheritance vs. Composition In such a situation, inheritance is not so appropriate. Obviously Car cannot be defined as a subclass of Tyre, nor Tyre as a subclass of Car. Composition is the mechanism by which the an instance (or instances) of the second concept is included in the data field of the first. That is, the Car class contains a Tyre object as one of its variables.

14 Polymorphism Polymorphism means ‘many forms’. A polymorphic variable is a variable whose declared type can be different from the type of the value it holds. Polymorphic variables are usually variables of a superclass holding object values of its subclass. Consider a situation where ‘Cat’ and ‘Dog’ are subclasses of ‘Animal’. Animal a Cat c Dog d a = c a = d The variable ‘a’ is polymorphic The assignment a=c will cause the data in the inherited fields to be copied to the superclass object, and ‘a’ will be considered as holding a subclass object (Cat).

15 If several functions or methods providing different functionalities are denoted by the same name, then that function is said to have been overloaded. A common form of method overloading is parametric overloading –where several function bodies exist with the same name, but are different in terms of the number of arguments or the types of arguments. –The compiler picks the correct function using the number and type of arguments supplied An overloaded operator is one which can accept different types of operands and perform different computations based on the operand types

16 A method in a superclass can be modified in the subclass (retaining the same name of the method), leading to another form of polymorphism known as method overriding. The modified method in the subclass is said to override the inherited behavior. The search for a method to invoke in response to a given message begins with the class of the receiver. If no appropriate method is found, the search is conducted in the parent class of this class. The search continues up the class hierarchy, until the method is found in a class.

17 If an overridden method is used with a polymorphic variable, then the method executed will depend on the type of the value which the variable currently holds Animal a Cat c Dog d a=c a.speak() …… a=d a.speak() The variable ‘a’ is polymorphic Invokes ‘speak’ method of ‘Cat’ class and prints ‘Meow’ Invokes ‘speak’ method of ‘Dog’ class and prints ‘Bow’ The message “a.speak( )” contains the overridden method ‘speak( )’ and a polymorphic variable ‘a’. The message has to be interpreted differently at run- time based on the type of the value ‘a’ holds. Polymorphisms of this type which are resolved at run-time are also sometimes call dynamic polymorphism

18 Code Class - class; access, members - function calls - constructor functions - decision making

19 Code Class >> class Class is a type – Aggregation of both data and functions General form: class Class_name { private: private_members; public: public_members; };

20 – Listed as in ordinary declarations Type and identifier in sequence – Class definition does NOT reserve memory for class members Memory reserved when class declared – Can be objects of other classes Code Class >> class class Elephant { private: char Stomach, Heart, Lungs; public: char Ears, Trunk, Toes; };

21 Code Class >> class – Private Restricts access of data to member functions – member data cannot be accessed directly from main – Public Allows member function to be called from main or any other function in program class Elephant { private: char Stomach, Heart, Lungs; public: char Ears, Trunk, Toes; };

22 Code Class >> function calls Function calls Each member function called must be associated with an object Example: object_name. function_name – object_name called invoking object Elephant jumbo; jumbo.set_peanut(4);

23 Code Class >> constructors Constructor – Class member function executed automatically upon declaration of object – Frequently used to initialize values of data members – Can be called just Constructor Characteristics – Name identical to class name – Does not return a value – Has public access – May or may not have arguments

24 Code Class >> constructors class Elephant { private: type data_member; public: Elephant ( ); type function_member ( ) ; }; Class Name and Constructor function name identical

25 Name : : Name ( ) { data_member = value; } Code Class >> constructors example of the constructor function refers to class refers to function

26 – Cannot return a value but can receive value through argument list – Function can assign value to data member – Passing a value to a constructor Code Class >> constructors Weather_station (int); Weather_station station (5); Weather_station : : Weather_station (int wind_speed_var) constructor function declaration constructor_name (type);

27 Code Class >> constructors Weather_station (int); Weather_station station (5); Weather_station : : Weather_station (int wind_speed_var) Constructor function call constructor function (value);

28 Code Class >> constructors Overloading constructor functions – Can have two or more constructor functions in class definition – Default copy constructor automatically executed when one object declared to be identical to another – Distinguishable in terms of number or type of arguments Elephant ( ) ; Elephant (int); Elephant (int, int); Elephant (int, double);

29 Code Class >> decision making simple if statement relational and logical operators simple if-else nested if-else if-else-if

30 Code Class >> decision making Simple if statement – Capable of making decisions – Relational expression evaluated Evaluated as true or false if (relational expression) { statement(s); } if result true execute statement if false, skip it

31 Code Class >> decision making Relational Expression – Type of logical expression Produces result of true or false – Compares values of two arithmetic expressions left_operand relational_operator right_operand e.g. if (amount<1000) if (name==”gerrard”) if (age >18)

32 Relational Operators <less than <=less than or equal to ==equal to >greater than >=greater than or equal to !=not equal Code Class >> decision making

33 Logical Operators – Exclamation mark ! NOT(negation) unary – Two ampersands && AND(conjunction) binary – Two vertical pipes || OR(inclusive disjunction) binary Code Class >> decision making

34 – Reverses result of relational expression – Example: ! (x == y) Code Class >> decision making if x=4 and y=4 (x==y) would return true !(x==y) would return false answer : false if x=4 and y=7 (x==y) would return false !(x==y) would return true answer : true

35 Code Class >> decision making Logical OR operator – Combines two relational expressions – Combined expression true only if BOTH expressions are true true && truetrue false &&falsefalse true&&falsefalse false &&truefalse

36 Code Class >> decision making Logical OR Operator – Combines two relational expressions – Combined expression false only if BOTH expressions are false true && truetrue false &&falsefalse true&&falsetrue false &&truetrue

37 Code Class >> decision making e.g if (team==”germany”) {result=”lose”; } ---------------------------------- if (team != “germany”) {result=”win”; } ---------------------------------- if (score<”70” && attendance<”75%”) {action=”suspend”; } ---------------------------------- if (count<40) {++count; }

38 – Result of relational expression False, C++ compiler gives zero True, C++ compiler gives one – Value of relational expression Zero, result is false Nonzero, result is true – any number other than zero, including negatives Code Class >> decision making

39 – logical value False if value is 0 True if value is nonzero if (c) statement1; else statement2; if c=0 execute statement 1 if c=1,2,3..... execute statement 2

40 Code Class >> decision making Simple if/else – block of statements to be executed for either true OR false – Braces optional if only one statement in block if (expression) { statement1a; statement1b; … } else { statement1a; statement1b; … }

41 Code Class >> decision making if (expression) { statement1a; statement1b; … } else { statement1a; statement1b; … } if expression is true

42 Code Class >> decision making if (expression) { statement1a; statement1b; … } else { statement1a; statement1b; … } if expression is false

43 Code Class >> decision making – x = 3; – if (x < 2) – { – cout << “x is smaller than 2”; – } Simple if – statements only done on true, but when false, skips to end of if  if (x < 12)  cout << “smaller than twelve”  else  cout << “twelve or larger”; Full if – code for when true and also when false

44 Code Class >> decision making Ternary Operator – Three operands needed for proper usage – Conditional ? : operator Question mark separates relational expression from rest of statement Colon separates two operands expression1? expression2 : expression3

45 Code Class >> decision making expression1? expression2 : expression3 separates relational expressions from rest of statement separates two operands x = (y < z) ? y : z

46 Code Class >> decision making if (a > b) { ans = 10;} else { ans = 25;} a > b ? (ans = 10) : (ans = 25) ans = (a > b) ? 10 : 25

47 Code Class >> decision making if (outer) { … if (inner) { … } else { … } } else { … }

48 Code Class >> decision making if (outer) { … if (inner) { … } else { … } } else { … } if outer is true, check this part

49 Code Class >> decision making if (outer) { … if (inner) { … } else { … } } else { … } else, do this part

50 Code Class >> decision making If-else-if – Shifts program control, step by step, through series of statement blocks – Control stops at relational expression that tests true

51 Code Class >> decision making if (relational_expression_1) { statement_block_1 } else if (relational_expression_2) { statement_block_2 }. else if (relational_expression_n-1) { statement_block_n-1 } else { statement_block_n }

52 Code Class >> decision making Switch control structure – Constructed like if-else-if – Used to transfer control – Can nest switch control structures – Keyword switch followed by expression switch (expression) { statement block }

53 Code Class >> decision making switch (expression) {case constant1: statement1a statement1b … case constant2: statement2a statement2b … default: statements } – Keyword case only used in switch statement – case used to form label – case label is constant followed by colon – Constant1, constant2, etc must be integer expressions – Constant expressions must be unique – default optional, used when no match is found

54 switch (option) { case (1) : cout << “Entering case 1”;..... case (2) : cout << “Entering case 2”;..... case (3) : cout << “Entering case 3”;..... default : cout << “default case”; } Code Class >> decision making

55 switch (expression) {case constant1: statement1a break; case constant2: statement2a break; … default: statements } Break Statement – Terminates execution of switch statement – Sends control to point of closing brace – Usually last statement for each case – If no break, then statements in next case executed

56 END : go back to first slide and start All Over Again =]


Download ppt "DCS 5085 Class Hierarchy Chapter 3. Overview Inheritance Why Inheritance Forms of Inheritance Advantages and Disadvantages Inheritance vs. Composition."

Similar presentations


Ads by Google