Presentation is loading. Please wait.

Presentation is loading. Please wait.

Object-Oriented Programming: Inheritance

Similar presentations


Presentation on theme: "Object-Oriented Programming: Inheritance"— Presentation transcript:

1 Object-Oriented Programming: Inheritance
11 Object-Oriented Programming: Inheritance Many slides modified by Prof. L. Lilien (even many without an explicit note). Slides added by L.Lilien are © Leszek T. Lilien. Permision to use for non-commercial purposes slides added by L.Lilien’s will be gladly granted upon a written (e.g., ed) request.

2 11.1   Introduction 11.2   Base Classes and Derived Classes 11.3   protected Members [and internal Members] 11.4   Relationship between Base Classes and Derived Classes Case Study: Three-Level Inheritance Hierarchy 11.5   Constructors [and Destructors] in Derived Classes 11.6   Software Engineering with Inheritance 11.7   Class object

3 an inheritance hierarchy
11.1. Introduction Inheritance: A new class (NC) can be created by “inheriting” (absorbing) the methods and variables of an existing class Terms: Base class Derived class (Class) inheritance hierarchy an inheritance hierarchy vehicle car airplane ship ford gm chevrolet cadillac toyota

4 11.1. Introduction (Cont.) Inheritance:
A new class (NC) can be created by “inheriting” (absorbing) the methods and variables of an existing class NC then needs to add only its own fields and methods to specialize its capabilities Note: If we started developing NC from scratch, all fields and methods of NC would have to be created So inheritance saves time By reusing proven and debugged high-quality software NC is called a derived class bec. it derives (by inheritance) methods and variables from its base class Objects of derived class are objects of base class but not vice versa E.g. a ‘car’ object derived from a ‘vehicle’ object

5 An inheritance hierarchy
11.1  Introduction (Cont.) More terms: Direct base class — the base class which the derived class explicitly inherits. Indirect base class — any class above the direct base class in the inheritance hierarchy Direct/indirect derived class —analogously The class hierarchy actually begins with C# class object An inheritance hierarchy vehicle car airplane ship ford gm chevrolet cadillac toyota object

6 11.2. Base Classes and Derived Classes
An object of class C2 is often an object of another class C1 E.g., an object of a class Car is an object of a class Vehicle We say then that class C2 is derived from class C1, and that class C1 is base class for class C2 — Class Car is derived from class Vehicle — Class Vehicle is base class for class Car Every derived-class object is an object of its base class The inheritance hierarchy is tree-shaped Hierarchy is a tree in graph theory

7 11.2. Base Classes and Derived Classes (Cont.)
Specifying in C# that class car is derived from class vehicle: class car : vehicle Class constructors are not inherited A derived class can only access non-private base class members Unless it inherits accessor functions that allow for such access New classes can inherit from thousands of pre-built classes in class libraries Every class hierarchy has (implicitly) the object class at the top.

8 11.2. Base Classes and Derived Classes (Cont.)
Two important object relationships: “is-a” relationship: a derived class object can be treated as a base class object (e.g., a car is-a vehicle) Used in class inheritance hierarchies “has-a” relationship: class object has object references as members (e.g., a car has-a body, a car has-an engine) Used in class composition graphs

9 11.2 Base Classes and Derived Classes (Cont.)
Examples of base classes and derived classes. Note that base classes are “more general,” and derived classes are “more specific” (or specialized) Fig | Inheritance examples.

10 11.2 Base Classes and Derived Classes (Cont.)
An inheritance hierarchy representing a university community. Each arrow represents an is-a relationship. Fig | UML class diagram showing an inheritance hierarchy for university CommunityMembers.

11 11.2 Base Classes and Derived Classes (Cont.)
The Shape inheritance hierarchy We can follow the arrows to identify several is-a relationships. Fig | UML class diagram showing an inheritance hierarchy for Shape.

12 11.2 Base Classes and Derived Classes (Cont.)
Objects of all classes that extend a common base class can be treated as objects of that base class E.g., Circle, Square, Triangle extend TwoDimensionalShape However, base-class objects cannot be treated as objects of their derived classes. When a derived class needs a customized version of an inherited method, the derived class can override the base-class method.

13 11.2a. Example: Base Classes and Derived Classes
We shall implement Point and Circle classes in 2 ways: independently — Point.cs / PointTest.cs — Circle.cs / CircleTest.cs 2) using inheritance: — Point3.cs — Circle4.cs — CircleTest4.cs (really: Point3+Circle4Test)

14 Inheritance hierarchy for Point
Object (namespace: System) Point – p.348-ed.1 (private x, y) implicit inheritance Slide added by L. Lilien

15 Slide from ed.1 added by L. Lilien
1 // Fig. 9.4: Point.cs [textbook ed. 1] 2 // Point class represents an x-y coordinate pair. 3 4 using System; 5 6 // Point class definition implicitly inherits from Object (System.Object) 7 public class Point 8 { // point coordinates private int x, y; 11 // default constructor public Point() { // implicit call to base class constructor (i.e., Object constructor) occurs here // (to be explained later) } 17 // constructor public Point( int xValue, int yValue ) { // implicit call to Object constructor occurs here X = xValue; Y = yValue; } 25 // property X public int X { get { return x; } 33 X and Y coordinates declared private so other classes cannot directly access hem Default Point() constructor with implicit call to System’s Object constructor Constructor sets coordinates to parameters. Slide from ed.1 added by L. Lilien

16 Slide added by L. Lilien 34 set 35 {
{ x = value; // no need for validation } 38 } // end property X 40 // property Y public int Y { get { return y; } 48 set { y = value; // no need for validation } 53 } // end property Y 55 // return string representation of Point public override string ToString() { return "[" + x + ", " + y + "]"; } 61 62 } // end class Point Definition of overriding method ToString (overrides System’s Object.ToString) Slide added by L. Lilien

17 Output: 1 // Fig. 9.5: PointTest.cs [textbook ed. 1]
2 // Testing class Point. 3 4 using System; 5 using System.Windows.Forms; // needed by the “magic” MessageBox in Line 26 6 7 // PointTest class definition 8 class PointTest 9 { // main entry point for application static void Main( string[] args ) { // instantiate Point object Point point = new Point( 72, 115 ); 15 // display point coordinates via X and Y properties string output = "X coordinate is " + point.X + "\n" + "Y coordinate is " + point.Y; 19 point.X = 10; // set x-coordinate via X property point.Y = 10; // set y-coordinate via Y property 22 // display new point value output += "\n\nThe new location of point is " + point; 25 MessageBox.Show( output, "Demonstrating Class Point" ); // “Magic” MessageBox.Show displays a nice box (a form), puts output in it. } // end method Main 29 30 } // end class PointTest Create a Point object called ‘point’. Change coordinates of ‘point’ Calls the ToString method of class Point implicitly (ToString converts ‘point’ to string, bec. ‘output ‘is a string) Output: Slide from ed.1 added by L. Lilien

18 Inheritance hierarchy for Point and Circle classes
when Circle is implemented independently of Point Object (namespace: System) Point – p.348-ed.1 (private x, y) Circle - p.351-ed.1 implicit inheritance by L. LilienSlide added

19 Slide from ed.1 added by L. Lilien
1 // Fig. 9.6: Circle.cs [textbook ed. 1] 2 // Circle class contains x-y coordinate pair and radius. 3 4 using System; 5 6 // Circle class definition implicitly inherits from Object 7 public class Circle 8 { private int x, y; // coordinates of Circle's center private double radius; // Circle's radius 11 // default constructor public Circle() { // implicit call to base class constructor (i.e., Object constructor) occurs here // (to be explained later) } 17 // constructor public Circle( int xValue, int yValue, double radiusValue ) { // implicit call to Object constructor occurs here x = xValue; y = yValue; Radius = radiusValue; } 26 // property X public int X { get { return x; } 34 Slide from ed.1 added by L. Lilien

20 Slide from ed.1 added by L. Lilien
set { x = value; // no need for validation } 39 } // end property X 41 // property Y public int Y { get { return y; } 49 set { y = value; // no need for validation } 54 } // end property Y 56 // property Radius public double Radius { get { return radius; } 64 set { if ( value >= 0 ) // validation needed radius = value; } Slide from ed.1 added by L. Lilien

21 Slide from ed.1 added by L. Lilien
70 } // end property Radius 72 // calculate Circle diameter public double Diameter() { return radius * 2; } 78 // calculate Circle circumference public double Circumference() { return Math.PI * Diameter(); } 84 // calculate Circle area public double Area() { return Math.PI * Math.Pow( radius, 2 ); } 90 // return string representation of Circle public override string ToString() { return "Center = [" + x + ", " + y + "]" + "; Radius = " + radius; // returns, e.g., “Center = [34, 17]; Radius = 3” } 97 98 } // end class Circle Slide from ed.1 added by L. Lilien

22 Slide from ed.1 added by L. Lilien
1 // Fig. 9.7: CircleTest.cs [textbook ed. 1] 2 // Testing class Circle. 3 4 using System; 5 using System.Windows.Forms; // needed by the “magic” MessageBox in Line 42 6 7 // CircleTest class definition 8 class CircleTest 9 { // main entry point for application. static void Main( string[] args ) { // instantiate Circle Circle circle = new Circle( 37, 43, 2.5 ); 15 // get Circle's initial x-y coordinates and radius string output = "X coordinate is " + circle.X + "\nY coordinate is " + circle.Y + "\nRadius is " + circle.Radius; 20 // set Circle's x-y coordinates and radius to new values circle.X = 2; circle.Y = 2; circle.Radius = 4.25; 25 // display Circle's string representation output += "\n\nThe new location and radius of " + "circle are \n" + circle + "\n"; 29 // display Circle's diameter output += "Diameter is " + String.Format( "{0:F}", circle.Diameter() ) + "\n"; // F produces 2 decimal places by default (Fig. 4.19, p.152) Slide from ed.1 added by L. Lilien

23 Part 1 of Output Slide from ed.1 added by L. Lilien
1 // Fig. 9.7: CircleTest.cs [textbook ed. 1] 2 // Testing class Circle. 3 4 using System; 5 using System.Windows.Forms; 6 7 // CircleTest class definition 8 class CircleTest 9 { // main entry point for application. static void Main( string[] args ) { // instantiate Circle Circle circle = new Circle( 37, 43, 2.5 ); 15 // get Circle's initial x-y coordinates and radius string output = "X coordinate is " + circle.X + "\nY coordinate is " + circle.Y + "\nRadius is " + circle.Radius; 20 // change values of Circle's x-y coordinates and radius circle.X = 2; circle.Y = 2; circle.Radius = 4.25; 25 // display Circle's string representation output += "\n\nThe new location and radius of " + "circle are \n" + circle + "\n"; 29 // display Circle's diameter output += "Diameter is " + String.Format( "{0:F}", circle.Diameter() ) + "\n"; // F produces 2 decimal places by default (Fig. 4.19, p.152) Part 1 of Output Implicit call to circle’s ToString method (converts circle to string bec. output is a string) Slide from ed.1 added by L. Lilien

24 } Output (in a “magic” message box)
// display Circle's circumference output += "Circumference is " + String.Format( "{0:F}", circle.Circumference() ) + "\n"; 37 // display Circle's area output += "Area is " + String.Format( "{0:F}", circle.Area() ); 41 MessageBox.Show( output, "Demonstrating Class Circle" ); 43 } // end method Main 45 46 } // end class CircleTest Output (in a “magic” message box) } Shown as “Part 1 of Output” on the previous page Slide from ed.1 added by L. Lilien

25 Self-evaluation Exercise 1
Run both C# projects: 1) Point.cs / PointTest.cs 2) Circle.cs / CircleTest.cs Hints: In the “New Project” pop-up window of MS Visual Studio 2008, remember to select “Windows Forms Application” template for the programs. (The code uses MessageBox, which is a WFA feature). Hint for the Point project (analogous for Circle): Copy PointTest.cs code (from PointTest.txt from the online _downloads) into Program.cs project file (a tab in VS). Create new project file for Point.cs : (a) go to the Solutions Explorer VS window, (b) right click on the project name, (next to the C# icon), (c) select in turn: Add>>New Item>>Class). Copy Point.cs code (from Point.txt from the online _downloads) into new project file. Note: The online code in _downloads include the “namespace” declarations, which are not included in the code shown in this lecture above. In this case, these “namespace” declarations could be omitted and the program would still work (try it). Slide added by L. Lilien

26 Inheritance hierarchy for Point3
Object (namespace: System) Point3 – p.362-ed.1 (private x, y) implicit inheritance Slide added by L. Lilien

27 Slide from ed.1 added by L. Lilien
1 // Fig. 9.12: Point3.cs [textbook ed. 1] 2 // Point3 class represents an x-y coordinate pair. 3 4 using System; 5 6 // Point3 class definition implicitly inherits from Object 7 public class Point3 8 { // point coordinate private int x, y; 11 // default constructor public Point3() { // implicit call to base class constructor (i.e., Object constructor) occurs here // (to be explained later) } 17 // constructor public Point3( int xValue, int yValue ) { // implicit call to Object constructor occurs here X = xValue; // use property X Y = yValue; // use property Y } 25 // property X public int X { get { return x; } 33 Slide from ed.1 added by L. Lilien

28 Slide from ed.1 added by L. Lilien
set { x = value; // no need for validation } 38 } // end property X 40 // property Y public int Y { get { return y; } 48 set { y = value; // no need for validation } 53 } // end property Y 55 // return string representation of Point3 public override string ToString() { return "[" + X + ", " + Y + "]"; // uses properties X and Y unlike // Point.cs (which used variables x and y–-cf.Slide 16, Line 59) // Better s/w engineering if private variables accessed via properties. } 61 62 } // end class Point3 Slide from ed.1 added by L. Lilien

29 Inheritance hierarchy for Point3 and Circle4 classes
when Circle4 inherits from Point3 Object (namespace: System) Point3 – p.362-ed.1 (private x, y) Circle4 p.364-ed.1 (initializes x, y via Point3 constructor – see line 19) implicit inheritance explicit inheritance Slide added by L. Lilien

30 Slide from ed.1 added by L. Lilien
1 // Fig. 9.13: Circle4.cs [textbook ed. 1] 2 // Circle4 class that inherits from class Point3. 4 using System; 5 6 // Circle4 class definition inherits from Point3 7 public class Circle4 : Point3 8 { private double radius; 10 // default constructor public Circle4() { // implicit call to base class constructor (i.e.. Point constructor) occurs here // (to be explained later) } 16 // constructor public Circle4( int xValue, int yValue, double radiusValue ) : base( xValue, yValue ) // explicit call to base class constructor { Radius = radiusValue; } 23 // property Radius public double Radius { get { return radius; } 31 set { if ( value >= 0 ) // validation needed radius = value; Slide from ed.1 added by L. Lilien

31 Slide from ed.1 added by L. Lilien
} 37 } // end property Radius 39 // calculate Circle diameter public double Diameter() { return Radius * 2; // use property Radius } 45 // calculate Circle circumference public double Circumference() { return Math.PI * Diameter(); } 51 // calculate Circle area public virtual double Area() // declared virtual so it can be overridden { return Math.PI * Math.Pow( Radius, 2 ); // use property } 57 // return string representation of Circle4 public override string ToString() { // use base reference to return Point string representation return "Center= " + base.ToString() + "; Radius = " + Radius; // use property Radius } 65 66 } // end class Circle4 Circle4’s ToString method overrides inherited ToString method (i.e., Point3’s ToString method) Calls Point3’s ToString method to display coordinates Slide from ed.1 added by L. Lilien

32 Part 1 of Output: 1 // Fig. 9.14: CircleTest4.cs [textbook ed. 1]
2 // Testing class Circle4. 3 4 using System; 5 using System.Windows.Forms; // needed by the “magic” MessageBox in Line 43 6 7 // CircleTest4 class definition 8 class CircleTest4 9 { // main entry point for application static void Main( string[] args ) { // instantiate Circle4 Circle4 circle = new Circle4( 37, 43, 2.5 ); 15 // get Circle4's initial x-y coordinates and radius string output = "X coordinate is " + circle.X + "\n" + "Y coordinate is " + circle.Y + "\n" + "Radius is " + circle.Radius; 20 // set Circle4's x-y coordinates and radius to new values // via properties: X, Y, Radius -- not via private: x, y, radius circle.X = 2; circle.Y = 2; circle.Radius = 4.25; 25 // display Circle4's string representation output += "\n\n" + "The new location and radius of circle are " + "\n" + circle + "\n"; 30 // display Circle4's Diameter output += "Diameter is " + String.Format( "{0:F}", circle.Diameter() ) + "\n"; 34 Part 1 of Output: Change coordinates and radius of Circle4 object Implicit call to Circle4’s ToString method Call Circle’s Diameter method for output Slide from ed.1 added by L. Lilien

33 } Shown as “Part 1 of Output” on the previous page
// display Circle4's Circumference output += "Circumference is " + String.Format( "{0:F}", circle.Circumference() ) + "\n"; 38 // display Circle4's Area output += "Area is " + String.Format( "{0:F}", circle.Area() ); 42 MessageBox.Show( output, "Demonstrating Class Circle4" ); 44 } // end method Main 46 47 } // end class CircleTest4 Call Circle’s Circumference and Area methods for output } Shown as “Part 1 of Output” on the previous page Slide from ed.1 added by L. Lilien

34 Self-evaluation Exercise 2
Run the C# project including: Point3.cs / Circle4.cs / CircleTest4.cs Hints: In the “New Project” pop-up window of MS Visual Studio 2008, remember to select “Windows Forms Application” template for the programs. (The code uses MessageBox, which is a WFA feature). Copying code: Copy CircleTest4.cs code (from CircleTest4(Point3+Circle4Test).txt from the online _downloads) into Program.cs project file (a tab in VS). Create new project file for Point3.cs : (a) go to the Solutions Explorer VS window, (b) right click on the project name, (next to the C# icon), (c) select in turn: Add>>New Item>>Class). Copy Point3.cs code (from Point3.txt from the online _downloads) into new project file. Create new project file for Circle4.cs (similarly as for Point3 above). Copy Circle4.cs code (from Circle4.txt from the online _downloads) into new project file Note: The online code in _downloads include the “namespace” declaration, which are not included in the code shown in this lecture above. In this case, these “namespace” declarations could be omitted and the program would still work (try it). Slide added by L. Lilien

35 Self-evaluation Exercise 3
Extend the Point3-Circle4 hierarchy by adding to it the class Cylinder that inherits from Circle4. Hint: Cylinder should inherit Circle4’s x,y, and radius variables, and needs to add only the height variable. Object (namespace: System) Point3 (private x, y) Circle4 (initializes x, y via Point3 constructor) Cylinder (initializes x, y, radius via Circle4 constructor ) implicit inheritance explicit inheritance Slide added by L. Lilien

36 11.3. protected [and internal] Members
Recall: public and private members of a base class public member of a class: accessible anywhere that the program has a reference to an object of that class private member of a class : accessible only within the body of that class Accessing members of a base class by derived classes public member of a base class: directly accessible by derived-class methods and properties private member of a base class: not directly accessible by derived-class methods and properties

37 11.3. protected [and internal] Members (Cont.)
In addition to public and private, there are two intermediate (between public and private) levels of protection for members of a base class : protected member of a base class: accessible by base class or any class derived from that base class internal members of a base class: accessible by members of a base class, the derived classes and by any class in the same assembly Recall: The assembly = a package containing the MS Intermediate Language (MISL) code that a project has been compiled into, plus any other info that is needed for its classes

38 11.3 protected Members (Cont.)
** READ LATER** Software Engineering Observation 11.1 Properties and methods of a derived class cannot directly access private members of the base class. A derived class can change the state of private base-class fields only through non-private methods and properties provided in the base class. ** READ LATER** Software Engineering Observation 11.2 If a derived class could access its base class’s private fields, classes that inherit from that base class could access the fields as well. This would propagate access to what should be private fields, and the benefits of information hiding would be lost.

39 11.4. Relationship between Base Classes and Derived Classes
CommissionEmployee represents an employee who is paid a comission (a percentage of their sales).

40 ComissionEmployee (CE)
Object (namespace: System) ComissionEmployee (CE) From Fig. 11.4 private fN , lN, sSN, gS, cR NAME ABBREAVIATIONS (cf. p.502/ed.3) fN = firstName lN = lastName sSN = socialSecurityNumber gS = grossSales cR = comissionRate implicit inheritance Slide added by L. Lilien

41 Outline Commission Employee.cs (1 of 3 )
A colon (:) followed a class name at the end of the class declaration header indicates that the class inherits from the class to the right of the colon. NOTE: Usually inheritance from the object class is implicit (i.e., : object is usually omitted).

42 Outline Commission Employee.cs (2 of 3)

43 Outline Commission Employee.cs (3 of 3 )

44 11.4 Relationship between Base Classes and Derived Classes (Cont.)
RECALL: A colon (:) followed a class name at the end of the class declaration header indicates that the class extends the class to the right of the colon. Every C# class directly or indirectly inherits object’s methods. If a class does not specify that it inherits from another class, it implicitly inherits from object. Via direct inheritance

45 11.4 Relationship between Base Classes and Derived Classes (Cont.)
** READ LATER** Software Engineering Observation 11.3 When the class declaration does not explicitly extend a base class the compiler sets the base class of a class to object.

46 11.4 Relationship between Base Classes and Derived Classes (Cont.)
Declaring instance variables as private and providing public properties to manipulate and validate them helps enforce good software engineering Constructors are not inherited BUT… Either explicitly or implicitly, an inheriting class calls the base-class constructor E.g., when car created, call to vehicle‘s constructor made Even if a class does not have constructors, the default constructor will call the base class’s default constructor Class object’s default (empty) constructor does nothing

47 11.4 Relationship between Base Classes and Derived Classes (Cont.)
Method ToString for a class It is special—it is one of the methods that every class inherits directly or indirectly from class object It is returns a string representing object of the class Class object’s ToString method is primarily a placeholder that typically should be overridden by a derived class To override a base-class method, a derived class must declare an “overriding” method with keyword override The overriding method must have the same signature (method name, number of parameters and parameter types) and return type as the base-class method that it overrides

48 11.4 Relationship between Base Classes and Derived Classes (Cont.)
** READ LATER** Common Programming Error 11.1 It is a compilation error to override a method with a different access modifier. E.g., it is an error to override a public method with a protected or private method Reason: If a public method could be overridden as a protected or private method, the derived-class objects would not respond to the same method calls as base-class objects Bec. in the base class the method is public, and in derived class it is not (can’t be called “publically”, by any class anywhere)

49 11.4 Relationship between Base Classes and Derived Classes (Cont.)
Let’s tests class CommissionEmployee

50 Outline Commission EmployeeTest.cs (1 of 2)

51 Outline Output for testing class CommissionEmployee
Commission EmployeeTest.cs (2 of 2)

52 Self-evaluation Exercise 4
Run the C# project including: CommissionEmployee.cs (from Fig.11.4) / CommissionEmployeeTest.cs (from Fig. 11.5) (if necessary, see hints for previous self-evaluation exercises). Note: The online code in _downloads includes the explicit indication of inheritance from object as a part of the CommmisionEmployee class declaration. Namely, it includes “: object” declaration. It can be removed and the program will still work correctly (try it). Slide added by L. Lilien

53 11.4 Relationship between Base Classes and Derived Classes (Cont.)
We now declare and test a separate class BasePlusCommissionEmployee (Fig. 11.6), BasePlusCommissionEmployee class represents an employee that receives a base salary in addition to a commission.

54 ComissionEmployee (CE) From Fig.11.4 private fN , lN, sSN, gS, cR
Object (namespace: System) ComissionEmployee (CE) From Fig.11.4 private fN , lN, sSN, gS, cR BasePlusComissionEmployee (BPCE) From Fig.11.6 private fN , lN, sSN, gS, cR, bS NAME ABBREAVIATIONS fN = firstName lN = lastName sSN = socialSecurityNumber gS = grossSales cR = comissionRate bS = baseSalary implicit inheritance Slide added by L. Lilien

55 Outline BasePlus Commission Employee.cs (1 of 4)

56 Outline BasePlus Commission Employee.cs (2 of 4)

57 Outline BasePlus Commission Employee.cs (3 of 4)

58 Outline BasePlus Commission Employee.cs (4 of 4 )

59 11.4 Relationship between Base Classes and Derived Classes (Cont.)
Note the similarity between this class and class Commission­Employee (Fig. 11.4)—in this example, we do not yet exploit that similarity.

60 11.4 Relationship between Base Classes and Derived Classes (Cont.)
Testing class BasePlusCommissionEmployee

61 Outline BasePlusCommission EmployeeTest.cs (1 of 2)

62 Output for testing class BasePlusCommissionEmployee.
Outline Output for testing class BasePlusCommissionEmployee. BasePlusCommission EmployeeTest.cs (2of 2)

63 Self-evaluation Exercise 5
Run the C# project (no inheritance) : BasePlusCommissionEmployee.cs (from Fig. 11.6) / BasePlusCommissionEmployeeTest.cs (from Fig. 11.7) (if necessary, see hints for previous self-evaluation exercises) Slide added by L. Lilien

64 11.4 Relationship between Base Classes and Derived Classes (Cont.)
Much of the code for BasePlusCommissionEmployee is similar to the code for CommissionEmployee.

65 11.4 Relationship between Base Classes and Derived Classes (Cont.)
** READ LATER** Error-Prevention Tip 11.1 Copying and pasting code from one class to another can spread errors across multiple source-code files. Use inheritance rather than the “copy-and-paste”. ** READ LATER** Software Engineering Observation 11.4 With inheritance, the common members of all the classes in the hierarchy are declared in a base class. When changes are required for these common features, you need to make the changes only in the base class. Derived classes then inherit the changes. How convenient and effort-saving!

66 11.4 Relationship between Base Classes and Derived Classes (Cont.)
Now instead of declaring an “independent” new class BasePlusCommissionEmployee (as we did in Fig. 11.6), we declare class BasePlusCommissionEmployee, which inherits from class CommissionEmployee (of Fig. 11.4). We are reusing class CommissionEmployee !

67 ComissionEmployee (CE) From Fig.11.4 private fN , lN, sSN, gS, cR
Object (namespace: System) ComissionEmployee (CE) From Fig.11.4 private fN , lN, sSN, gS, cR public decimal Earnings() BasePlusComissionEmployee (BPCE) From Fig.11.8 private bS public override decimal Earnings() ERROR: Bec. tries to override method Earnings not marked as abstract, override or virtual in the base class implicit inheritance explicit inheritance NAME ABBREAVIATIONS (cf. p.502/ed.3) fN = firstName lN = lastName sSN = socialSecurityNumber gS = grossSales cR = comissionRate bS = baseSalary Slide added by L. Lilien

68 Outline BasePlusCommiss ionEmployee.cs (1 of 2 )
Class BasePlusCommissionEmployee has an additional instance variable baseSalary. Invoke the CommissionEmployee’s five-parameter constructor using a constructor initializer. BasePlusCommiss ionEmployee.cs (1 of 2 )

69 Outline BasePlusCommission Employee.cs (2 of 2 )

70 Self-evaluation Exercise 6
Run the C# project (with class inheritance) including: CommissionEmployee (from Fig. 11.4) BasePlusCommissionEmployee.cs (from Fig.11.8) / BasePlusCommissionEmployeeTest.cs (from Fig. 11.7) (if necessary, see hints for previous self-evaluation exercises) See that you get the error shown on the previous slide. Slide added by L. Lilien

71 ** READ LATER** 11.4  Relationship between Base Classes and Derived Classes (Cont.)
A BasePlusCommissionEmployee object is a CommissionEmployee. A constructor initializer with keyword base invokes the base-class constructor. ** READ LATER** Common Programming Error 11.2 A compilation error occurs if a derived-class constructor calls one of its base-class constructors with arguments that do not match the number and types of parameters specified in one of the base-class constructor declarations.

72 11.4 Relationship between Base Classes and Derived Classes (Cont.)
The virtual keywords(and the abstract keyword) indicate that a base-class method may be overridden in derived classes The override modifier declares that a derived-class method overrides a virtual or abstract base-class method This modifier also implicitly declares the derived-class method as virtual

73 11.4 Relationship between Base Classes and Derived Classes (Cont.)
Let’s fix this error as follows: Add the keyword virtual to the declaration of Earnings in CommissionEmployee (Fig. 11.4) Now, line 78 in Fig is: public virtual decimal Earnings() (instead of: public decimal Earnings() ) We have now the following situation: (next slide)

74 ComissionEmployee (CE) From updated Fig.11.4 (Note 1)
Object (namespace: System) ComissionEmployee (CE) From updated Fig.11.4 (Note 1) private fN , lN, sSN, gS, cR public virtual decimal Earnings() Note 1: The Update changed line 78 in Fig.11.4 to: public virtual decimal Earnings() BasePlusComissionEmployee (BPCE) From Fig. 11.8 private bS public override decimal Earnings() implicit inheritance explicit inheritance NAME ABBREAVIATIONS (cf. p.502/ed.3) fN = firstName lN = lastName sSN = socialSecurityNumber gS = grossSales cR = comissionRate bS = baseSalary Slide added by L. Lilien

75 11.4 Relationship between Base Classes and Derived Classes (Cont.)
Lets’ compile corrected BasePlusCommissionEmployee again The compiler generates additional errors for BasePlusCommissionEmployee Why these errors? — BasePlusCommissionEmployee attempts to directly access private CommissionEmployee’s instance variables: - In Line 34 (cR and gS ), in Line 43 (fN, lN), in Line 44 (sSN), and in Line 45 (gS, cR)

76 Self-evaluation Exercise 7
Run the C# project (with class inheritance) including: CommissionEmployee (from Fig updated) BasePlusCommissionEmployee.cs (from Fig.11.8) / BasePlusCommissionEmployeeTest.cs (from Fig. 11.7) (if necessary, see hints for previous self-evaluation exercises) See that you get the error sshown on the previous slide. Slide added by L. Lilien

77 11.4 Relationship between Base Classes and Derived Classes (Cont.)
Not recommended way to eliminate the compilation errors - Prevent them by having public instance variables in CommissionEmployee - Instead of private instance variables Not recommended since encapsulation/information hiding principle is violated Two better ways to eliminate the compilation errors: 1) They could be prevented by using the public properties inherited from class CommissionEmployee Instead of using direct access to private instance variables, access them via the corresponding public properties E.g. accessing private firstName instance variable via the corresponding public FirstName property 2) They can be prevented by having protected instance variables in CommissionEmployee (instead of private) Let’s modify Class CommissionEmployee in this way: Declare its instance variables as protected not as private (see Fig. 11.10)

78 ComissionEmployee (CE) From updated Fig. 11.4
Object (namespace: System) ComissionEmployee (CE) From updated Fig. 11.4 private fN , lN, sSN, gS, cR public decimal Earnings() ComissionEmployee2 (CE2) From Fig.11.10 protected fN , lN, sSN, gS, cR public virtual decimal Earnings() BasePlusComissionEmployee (BPCE) From Fig.11.8 private bS public override decimal Earnings() ERRORS because: missing virtual for Earnings in CE & tries to access private variables of CS implicit inheritance explicit inheritance NAME ABBREAVIATIONS fN = firstName lN = lastName sSN = socialSecurityNumber gS = grossSales cR = comissionRate bS = baseSalary Slide added by L. Lilien

79 Outline Commission Employee.cs ( 1 of 3)

80 Outline Commission Employee.cs ( 2 of 3)

81 Outline Commission Employee.cs ( 3 of 3)
We declare the Earnings method as virtual so that BasePlusCommissionEmployee can override this method.

82 11.4 Relationship between Base Classes and Derived Classes (Cont.)
Class BasePlusCommissionEmployee (Fig. 11.11) is modified to extend CommissionEmployee2. The instance variables are now protected members, so the compiler does not generate errors. Bec. now BasePlusCommissionEmployee inherits from CommissionEmployee2 and has access to CommissionEmployee2's protected members.

83 ComissionEmployee (CE) From updated Fig. 11.4
Object (namespace: System) ComissionEmployee (CE) From updated Fig. 11.4 private fN , lN, sSN, gS, cR public decimal Earnings() ComissionEmployee2 (CE2) From Fig.11.10 protected fN , lN, sSN, gS, cR public virtual decimal Earnings() BasePlusComissionEmployee (BPCE) From Fig.11.8 private bS public override decimal Earnings() ERRORS because: missing virtual for Earnings in CE & tries to access private variables of CS BasePlusComissionEmployee (BPCE) From Fig.11.11 private bS public override decimal Earnings() implicit inheritance explicit inheritance NAME ABBREAVIATIONS fN = firstName lN = lastName sSN = socialSecurityNumber gS = grossSales cR = comissionRate bS = baseSalary (cf. p.517/ed.3) Slide added by L. Lilien

84 Outline BasePlusCommiss ionEmployee.cs ( 1 of 2 )
BasePlusCommissionEmployee inherits here from CommissionEmployee2 (instead of inheriting from CommissionEmployee). The rest of BasePlusCommissionEmployee of this figure is the same as in Fig.11.8.

85 Outline BasePlusCommissi onEmployee.cs ( 2 of 2 )

86 11.4 Relationship between Base Classes and Derived Classes (Cont.)
Figure 11.12 tests a BasePlusCommissionEmployee object. While the output is identical, there is less code repetition and overall this is a better implementation.

87 Outline NOTE: Incorrect name. Should be:
BasePlusCommissionEmployeeTest BasePlusCommissio nEmployee.cs ( 1 of 3 )

88 Outline BasePlusCommissio nEmployee.cs ( 2 of 3 ) Output for the testing class BasePlusCommissionEmployee. (Part 3 of 3.)

89 Self-evaluation Exercise 8
Run the C# project (with class inheritance) including: CommissionEmployee2 (from Fig.11.10) BasePlusCommissionEmployee.cs (from Fig.11.11) / BasePlusCommissionEmployee[Test].cs (from Fig ) (if necessary, see hints for previous self-evaluation exercises) See that you get the correct output as shown on the previous slide. Slide added by L. Lilien

90 11.4 Relationship between Base Classes and Derived Classes (Cont.)
CE2 uses protected instance variables firstName, lastName, etc. to allow BPCE (and other derived-class objects) direct access to firstName, lastName, etc Also (a bit) faster execution for direct access than access via properties and their set / get accessors It works correctly but… …problems with protected instance variables: 1) derived-class objects can assign illegal value to the protected data 2) software becomes brittle / fragile: change of base-class implementation forces changes of implementations of derived-classes (should not force changes!) — Here: changing names of firstName, lastName to, e.g., givenName, familyName So, let’s write CE and BPCE that work correctly with private, not protected instance variables firstName, lastName, etc.

91 11.4 Relationship between Base Classes and Derived Classes (Cont.)
** READ LATER** Software Engineering Observation 11.5 Declaring base-class instance variables as ‘private’ enables the base-class implementation of these instance variables to change without affecting derived-class implementations. QUESTION: How to avoid errors we have seen with private instance variables? ANSWER: Access private instance variables via their corresponding public properties

92 11.4 Relationship between Base Classes and Derived Classes (Cont.)
Class CommissionEmployee (Fig. 11.13) is modified to declare private instance variables and provide public properties.

93 ComissionEmployee (CE)
Object (namespace: System) CE code shown below (Fig , p.520). NOTE: This CE is similar to CE of Fig .11.4, p.502 – BUT it is: not using explicit “: object” in Line 3, having “virtual” in Line 78. Earnings method accesses instance variables via properties, not directly, in Line 80 ComissionEmployee (CE) From Fig.11.13 private fN , lN, sSN, gS, cR public virtual decimal Earnings() implicit inheritance explicit inheritance NAME ABBREAVIATIONS fN = firstName lN = lastName sSN = socialSecurityNumber gS = grossSales cR = comissionRate bS = baseSalary (cf. p.517/ed.3) Slide added by L. Lilien

94 Outline Commission Employee.cs ( 1 of 3 )

95 Outline Commission Employee.cs ( 2 of 3 )

96 Outline Commission Employee.cs ( 3 of 3 )
Use the class’s properties to obtain the values of its instance variables.

97 11.4 Relationship between Base Classes and Derived Classes (Cont.)
New implementation of class BasePlusCommissionEmployee (Fig. 11.14) inheriting from the above CommissionEmployee has several changes to its method implementations (see next page).

98 ComissionEmployee (CE) From Fig.11.13 private fN , lN, sSN, gS, cR
Object (namespace: System) BPCE code shown below (Fig , p.522). NOTE: This BPCE is different than BPCE of Fig , p.517. Differences: one more comment line (4 not 3) inheriting from the above CE not from CE2 (Line 5) Earnings() does not access baseSalary instance variable directly but uses BaseSalary property (Line 35) Earnings() does not access comissionRate and grossSales instance variables directly but calls base.Earnings() that accesses them (via their properties) (Line 35) ToString() does not use 5 base class properties directly but calls base.ToString() (Line 42) ComissionEmployee (CE) From Fig.11.13 private fN , lN, sSN, gS, cR public virtual decimal Earnings() BasePlusComissionEmployee (BPCE) From Fig.11.14 private bS public override decimal Earnings() implicit inheritance explicit inheritance NAME ABBREAVIATIONS fN = firstName lN = lastName sSN = socialSecurityNumber gS = grossSales cR = comissionRate bS = baseSalary (cf. p.517/ed.3) Slide added by L. Lilien

99 Outline BasePlusCommissio nEmployee.cs ( 1 of 2 )

100 Outline BasePlusCommissio nEmployee.cs ( 2 of 2 )
Use CommissionEmployee’s Earnings method to calculate the commission pay, and add it to the BaseSalary. Outline BasePlusCommissio nEmployee.cs ( 2 of 2 ) Use CommissionEmployee’s ToString method to display BasePlusCommissionEmployee .

101 11.4 Relationship between Base Classes and Derived Classes (Cont.)
** READ LATER** Common Programming Error 11.3 When a base-class method is overridden in a derived class, the derived-class version often calls the base-class version to do a portion of the work Failure to prefix the base-class method name with the keyword base when referencing the base class’s method causes the derived-class method to call itself ** READ LATER** Common Programming Error 11.4 It is a compilation error to use “chained” base references to refer to a member several levels up the hierarchy — E.g. base.base.Earnings()

102 11.4 Relationship between Base Classes and Derived Classes (Cont.)
Fig.  11.15 performs testing of the BasePlusCommissionEmployee class. By using inheritance and properties, we have efficiently and effectively constructed a well-engineered class.

103 Outline BasePlusCommissio nEmployeeTest.cs ( 1 of 2 )

104 Outline Output for testing class BasePlusCommissionEmployee.
BasePlusCommissio nEmployeeTest.cs ( 2 of 2 )

105 Self-evaluation Exercise 9
Run the C# project (with class inheritance) including: CommissionEmployee (from Fig.11.13) BasePlusCommissionEmployee.cs (from Fig.11.14) / BasePlusCommissionEmployeeTest.cs (from Fig ) (if necessary, see hints for previous self-evaluation exercises) See that you get the correct output as shown on the previous slide. Slide added by L. Lilien

106 11.4 Relationship between Base Classes and Derived Classes (Cont.)
Benefits of inheritance: Using inheritance hierarchy in the above CE-BPCE inheritance hierarchy example, we were able to develop BPCE (inheriting from CE) much more quickly than if we had developed the BPCE class from scratch Inheritance avoids duplicating code and associated code-maintenance problems Such as the need to modify implementations all derived classes when the implementations of the base class changes Slide added by L. Lilien

107 11.5 Constructors [and Destructors] in Derived Classes
Instantiating a derived class DC, causes base-class constructor to be called — implicitly or explicitly When a constructor of a derived class DC is called, it invokes the derived class’ base-class destructor first Only then it performs its own tasks Causes chain reaction when a base class is also a derived class The object class constructor (at the top of the inheritance chain) is called last BUT The object class constructor actually finishes first The DC class constructor (called first) finishes last Consider example: Object - CommissionEmployee –BasePlusCommissionEmployee

108 11.5 Constructors [and Destructors] in Derived Classes (Cont.)
** READ LATER** Software Engineering Observation 11.6 When an application creates a derived-class object, the derived-class constructor calls the base-class constructor Calls it either explicitly (using base), or implicitly The base-class constructor’s body executes to initialize the base class’s instance variables that are part of the derived-class object, then the derived class constructor’s body executes to initialize the derived-class-only instance variables Even if a constructor does not assign a value to an instance variable, the variable is still initialized to its default value

109 11.5 Constructors [and Destructors] in Derived Classes (Cont.)
Class CommissionEmployee of Fig is modified into class CommissionEmployee of Fig.11.16 Modification (highlighted in Fig below): to output a message when CE’s constructor is invoked This output is for educational purposes —to show how constructors work

110 Outline Commission Employee.cs ( 1 of 3 )

111 Outline Commission Employee.cs ( 2 of 3 )

112 Outline Commission Employee.cs ( 3 of 3 )

113 11.5 Constructors [and Destructors] in Derived Classes (Cont.)
Class BasePlusCommissionEmployee of Fig. 11.14 is modified into class BasePlusCommissionEmployee of Fig. 11.17 Modification (highlighted in Fig below): to output a message when BPCE’s constructor is invoked Again, this output is for educational purposes—to show how constructors work

114 Outline BasePlusCommissio nEmployee.cs ( 1 of 3 )

115 Outline BasePlusCommissio nEmployee.cs ( 3 of 3 )

116 11.5 Constructors [and Destructors] in Derived Classes (Cont.)
ConstructorTest in Figure 11.18 demonstrates the order in which constructors are called in an inheritance hierarchy Displays order in which base-class and derived-class constructors are called.

117 Outline Constructor Test.cs ( 1 of 3 )

118 Outline Top-level class (no explicit class above it in the inheritance hierarchy) – only 1 constructor called for Bob Constructor Test.cs ( 2 of 3 ) 2nd-level class (inherits from one explicit class above it in the inheritance hierarchy) – 2 constructors called for Lisa

119 Outline 2nd-level class (inherits from one explicit class above it in the inheritance hierarchy) – 2 constructors called for Mark Constructor Test.cs ( 3 of 3 )

120 ++OPTIONAL++ 11.5  Constructors [and Destructors] in Derived Classes (Cont.)
Cf. p in Ch.10 (ed.3) When a destructor (or finalizer) of a derived class DC is called, it performs its own tasks first Then invokes the derived class’ base-class destructor Causes chain reaction when a base class is also a derived class The DC class destructor (called first) finishes its tasks first The Object class destructor (at the top of the inheritance chain) is called last AND The Object class destructor actually finishes its tasks last Each class has a destructor : if not explicit then implicit e.g., consider: object - CommissionEmployee –BasePlusCommissionEmployee NOTE: Unlike in C or C++, memory management in C# is performed automatically => memory leaks are rare in C# Memory mgmt via garbage collection of objects for which no references exist (p.312/1)

121 11.6. Software Engineering with Inheritance
Derived classes inherit from the existing class Member variables Properties Methods One can customize derived classes to meet one’s needs by: Creating new member variables Creating new properties Creating new methods Overriding base-class members .NET Framework Class Library (FCL) allows full reuse of software through inheritance Big benefits in software development (faster, more reliable, …) Class libraries deliver the maximum benefits of software reuse Independent software vendors (ISVs) can develop and sell proprietary classes • Users then can derive new classes from these library classes without accessing the source code. Read Section 11.6 / Read Section 11.8 Wrap-up

122 11.6 Software Engineering with Inheritance (Cont.)
** READ LATER** Software Engineering Observation 11.7 Although inheriting from a class does not require access to the class’s source code, developers often insist on seeing the source code to understand how the class is implemented They may, for example, want to ensure that they are extending a class that performs well and is implemented securely Effective software reuse greatly improves the software-development process Object-oriented programming facilitates software reuse

123 11.6 Software Engineering with Inheritance (Cont.)
** READ LATER** Software Engineering Observation 11.8 At the design stage in an object-oriented system, the designer often finds that certain classes are closely related The designer should “factor out” common members and place them in a base class. ** READ LATER** Software Engineering Observation 11.9 Declaring a derived class does not affect its base class’s source code Inheritance preserves the in­tegrity of the base class

124 11.6 Software Engineering with Inheritance (Cont.)
** READ LATER** Software Engineering Observation 11.10 Designers of object-oriented systems should avoid class proliferation (i.e., having huge class libraries) Such proliferation creates management problems It can also can hinder software reusability Because in a huge class library it becomes difficult to locate the most appropriate classes ** READ LATER** Performance Tip 11.1 If derived classes are larger than they need to be (i.e., contain too much functionality), memory and processing resources might be wasted Extend the base class containing the functionality that is closest to what is needed (not more, or — at least— not much more)

125 11.7. Class object All classes inherit (directly or not) from the object class 7 methods of the object class (inherited by all objects!) See: a) Public Methods Equals - Overloaded. Determines whether two object instances are equal GetHashCode - Serves as a hash function for a particular type GetType - Gets the Type of the current instance ReferenceEquals - Determines whether the specified object instances are the same instance ToString - Returns a String that represents the current object b) Protected Methods Finalize - Allows an object to attempt to free resources and perform other cleanup operations before the object is reclaimed by garbage collection MemberwiseClone - Creates a “shallow copy” of the current object.

126 11.7  Class object (Cont.) Methods of the object class — inherited (directly or indirectly) by all classes

127 The End


Download ppt "Object-Oriented Programming: Inheritance"

Similar presentations


Ads by Google