Download presentation
Presentation is loading. Please wait.
1
2009 Pearson Education, Inc. All rights reserved. 1 11 Object-Oriented Programming: Inheritance Many slides modified by Prof. L. Lilien (even many without an explicit note). Slides added by L.Lilien are © 2006-2009 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., emailed) request.
2
2009 Pearson Education, Inc. All rights reserved. 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
2009 Pearson Education, Inc. All rights reserved. 3 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 carairplaneship fordgm chevroletcadillac toyota …… … …
4
2009 Pearson Education, Inc. All rights reserved. 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
2009 Pearson Education, Inc. All rights reserved. 5 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 carairplaneship fordgm chevroletcadillac toyota … … object … … … …
6
2009 Pearson Education, Inc. All rights reserved. 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
2009 Pearson Education, Inc. All rights reserved. 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
2009 Pearson Education, Inc. All rights reserved. 8 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 11.2. Base Classes and Derived Classes (Cont.)
9
2009 Pearson Education, Inc. All rights reserved. 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. 11.1 | Inheritance examples.
10
2009 Pearson Education, Inc. All rights reserved. 10 11.2 Base Classes and Derived Classes (Cont.) An inheritance hierarchy representing a university community. Each arrow represents an is-a relationship. Fig. 11.2 | UML class diagram showing an inheritance hierarchy for university CommunityMember s.
11
2009 Pearson Education, Inc. All rights reserved. 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. 11.3 | UML class diagram showing an inheritance hierarchy for Shape.
12
2009 Pearson Education, Inc. All rights reserved. 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
2009 Pearson Education, Inc. All rights reserved. 13 11.2a. Example: Base Classes and Derived Classes We shall implement Point and Circle classes in 2 ways: 1)independently — Point.cs / PointTest.cs — Circle.cs / CircleTest.cs 2) using inheritance: — Point3.cs — Circle4.cs — CircleTest4.cs (really: Point3+Circle4Test)
14
2009 Pearson Education, Inc. All rights reserved. 14 Object (namespace: System) Point – p.348-ed.1 (private x, y) implicit inheritance Slide added by L. Lilien Inheritance hierarchy for Point
15
2009 Pearson Education, Inc. All rights reserved. 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 { 9 // point coordinates 10 private int x, y; 11 12 // default constructor 13 public Point() 14 { 15 // implicit call to base class constructor (i.e., Object constructor) occurs here // (to be explained later) 16 } 17 18 // constructor 19 public Point( int xValue, int yValue ) 20 { 21 // implicit call to Object constructor occurs here 22 X = xValue; 23 Y = yValue; 24 } 25 26 // property X 27 public int X 28 { 29 get 30 { 31 return x; 32 } 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.
16
2009 Pearson Education, Inc. All rights reserved. 16 Slide added by L. Lilien 34 set 35 { 36 x = value; // no need for validation 37 } 38 39 } // end property X 40 41 // property Y 42 public int Y 43 { 44 get 45 { 46 return y; 47 } 48 49 set 50 { 51 y = value; // no need for validation 52 } 53 54 } // end property Y 55 56 // return string representation of Point 57 public override string ToString() 58 { 59 return "[" + x + ", " + y + "]"; 60 } 61 62 } // end class Point Definition of overriding method ToString (overrides System’s Object.ToString)
17
2009 Pearson Education, Inc. All rights reserved. 17 Slide from ed.1 added by L. Lilien 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 { 10 // main entry point for application 11 static void Main( string[] args ) 12 { 13 // instantiate Point object 14 Point point = new Point( 72, 115 ); 15 16 // display point coordinates via X and Y properties 17 string output = "X coordinate is " + point.X + 18 "\n" + "Y coordinate is " + point.Y; 19 20 point.X = 10; // set x-coordinate via X property 21 point.Y = 10; // set y-coordinate via Y property 22 23 // display new point value 24 output += "\n\nThe new location of point is " + point; 25 26 MessageBox.Show( output, "Demonstrating Class Point" ); 27 // “Magic” MessageBox.Show displays a nice box (a form), puts output in it. 28 } // end method Main 29 30 } // end class PointTest Output: Calls the ToString method of class Point implicitly (ToString converts ‘ point ’ to string, bec. ‘output ‘is a string) Create a Point object called ‘point’. Change coordinates of ‘point’
18
2009 Pearson Education, Inc. All rights reserved. 18 Object (namespace: System) Point – p.348-ed.1 (private x, y) Circle - p.351-ed.1 implicit inheritance by L. LilienSlide added Inheritance hierarchy for Point and Circle classes when Circle is implemented independently of Point
19
2009 Pearson Education, Inc. All rights reserved. 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 { 9 private int x, y; // coordinates of Circle's center 10 private double radius; // Circle's radius 11 12 // default constructor 13 public Circle() 14 { 15 // implicit call to base class constructor (i.e., Object constructor) occurs here // (to be explained later) 16 } 17 18 // constructor 19 public Circle( int xValue, int yValue, double radiusValue ) 20 { 21 // implicit call to Object constructor occurs here 22 x = xValue; 23 y = yValue; 24 Radius = radiusValue; 25 } 26 27 // property X 28 public int X 29 { 30 get 31 { 32 return x; 33 } 34
20
2009 Pearson Education, Inc. All rights reserved. 20 Slide from ed.1 added by L. Lilien 35 set 36 { 37 x = value; // no need for validation 38 } 39 40 } // end property X 41 42 // property Y 43 public int Y 44 { 45 get 46 { 47 return y; 48 } 49 50 set 51 { 52 y = value; // no need for validation 53 } 54 55 } // end property Y 56 57 // property Radius 58 public double Radius 59 { 60 get 61 { 62 return radius; 63 } 64 65 set 66 { 67 if ( value >= 0 ) // validation needed 68 radius = value; 69 }
21
2009 Pearson Education, Inc. All rights reserved. 21 Slide from ed.1 added by L. Lilien 70 71 } // end property Radius 72 73 // calculate Circle diameter 74 public double Diameter() 75 { 76 return radius * 2; 77 } 78 79 // calculate Circle circumference 80 public double Circumference() 81 { 82 return Math.PI * Diameter(); 83 } 84 85 // calculate Circle area 86 public double Area() 87 { 88 return Math.PI * Math.Pow( radius, 2 ); 89 } 90 91 // return string representation of Circle 92 public override string ToString() 93 { 94 return "Center = [" + x + ", " + y + "]" + 95 "; Radius = " + radius; // returns, e.g., “Center = [34, 17]; Radius = 3” 96 } 97 98 } // end class Circle
22
2009 Pearson Education, Inc. All rights reserved. 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 { 10 // main entry point for application. 11 static void Main( string[] args ) 12 { 13 // instantiate Circle 14 Circle circle = new Circle( 37, 43, 2.5 ); 15 16 // get Circle's initial x-y coordinates and radius 17 string output = "X coordinate is " + circle.X + 18 "\nY coordinate is " + circle.Y + "\nRadius is " + 19 circle.Radius; 20 21 // set Circle's x-y coordinates and radius to new values 22 circle.X = 2; 23 circle.Y = 2; 24 circle.Radius = 4.25; 25 26 // display Circle's string representation 27 output += "\n\nThe new location and radius of " + 28 "circle are \n" + circle + "\n"; 29 30 // display Circle's diameter 31 output += "Diameter is " + 32 String.Format( "{0:F}", circle.Diameter() ) + "\n"; 33 // F produces 2 decimal places by default (Fig. 4.19, p.152)
23
2009 Pearson Education, Inc. All rights reserved. 23 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 { 10 // main entry point for application. 11 static void Main( string[] args ) 12 { 13 // instantiate Circle 14 Circle circle = new Circle( 37, 43, 2.5 ); 15 16 // get Circle's initial x-y coordinates and radius 17 string output = "X coordinate is " + circle.X + 18 "\nY coordinate is " + circle.Y + "\nRadius is " + 19 circle.Radius; 20 21 // change values of Circle's x-y coordinates and radius 22 circle.X = 2; 23 circle.Y = 2; 24 circle.Radius = 4.25; 25 26 // display Circle's string representation 27 output += "\n\nThe new location and radius of " + 28 "circle are \n" + circle + "\n"; 29 30 // display Circle's diameter 31 output += "Diameter is " + 32 String.Format( "{0:F}", circle.Diameter() ) + "\n"; 33 // F produces 2 decimal places by default (Fig. 4.19, p.152) Implicit call to circle’s ToString method (converts circle to string bec. output is a string) Part 1 of Output
24
2009 Pearson Education, Inc. All rights reserved. 24 Slide from ed.1 added by L. Lilien 34 // display Circle's circumference 35 output += "Circumference is " + 36 String.Format( "{0:F}", circle.Circumference() ) + "\n"; 37 38 // display Circle's area 39 output += "Area is " + 40 String.Format( "{0:F}", circle.Area() ); 41 42 MessageBox.Show( output, "Demonstrating Class Circle" ); 43 44 } // end method Main 45 46 } // end class CircleTest Output (in a “magic” message box) } Shown as “Part 1 of Output” on the previous page
25
2009 Pearson Education, Inc. All rights reserved. 25 Slide added by L. Lilien Self-evaluation Exercise 1 Run both C# projects: 1) Point.cs / PointTest.cs 2) Circle.cs / CircleTest.cs Hints: 1)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). 2)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).
26
2009 Pearson Education, Inc. All rights reserved. 26 Object (namespace: System) Point3 – p.362-ed.1 (private x, y) implicit inheritance Slide added by L. Lilien Inheritance hierarchy for Point3
27
2009 Pearson Education, Inc. All rights reserved. 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 { 9 // point coordinate 10 private int x, y; 11 12 // default constructor 13 public Point3() 14 { 15 // implicit call to base class constructor (i.e., Object constructor) occurs here // (to be explained later) 16 } 17 18 // constructor 19 public Point3( int xValue, int yValue ) 20 { 21 // implicit call to Object constructor occurs here 22 X = xValue; // use property X 23 Y = yValue; // use property Y 24 } 25 26 // property X 27 public int X 28 { 29 get 30 { 31 return x; 32 } 33
28
2009 Pearson Education, Inc. All rights reserved. 28 Slide from ed.1 added by L. Lilien 34 set 35 { 36 x = value; // no need for validation 37 } 38 39 } // end property X 40 41 // property Y 42 public int Y 43 { 44 get 45 { 46 return y; 47 } 48 49 set 50 { 51 y = value; // no need for validation 52 } 53 54 } // end property Y 55 56 // return string representation of Point3 57 public override string ToString() 58 { 59 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. 60 } 61 62 } // end class Point3
29
2009 Pearson Education, Inc. All rights reserved. 29 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) Slide added by L. Lilien Inheritance hierarchy for Point3 and Circle4 classes when Circle4 inherits from Point3 implicit inheritance explicit inheritance
30
2009 Pearson Education, Inc. All rights reserved. 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. 3 4 using System; 5 6 // Circle4 class definition inherits from Point3 7 public class Circle4 : Point3 8 { 9 private double radius; 10 11 // default constructor 12 public Circle4() 13 { 14 // implicit call to base class constructor (i.e.. Point constructor) occurs here // (to be explained later) 15 } 16 17 // constructor 18 public Circle4( int xValue, int yValue, double radiusValue ) 19 : base( xValue, yValue ) // explicit call to base class constructor 20 { 21 Radius = radiusValue; 22 } 23 24 // property Radius 25 public double Radius 26 { 27 get 28 { 29 return radius; 30 } 31 32 set 33 { 34 if ( value >= 0 ) // validation needed 35 radius = value;
31
2009 Pearson Education, Inc. All rights reserved. 31 Slide from ed.1 added by L. Lilien 36 } 37 38 } // end property Radius 39 40 // calculate Circle diameter 41 public double Diameter() 42 { 43 return Radius * 2; // use property Radius 44 } 45 46 // calculate Circle circumference 47 public double Circumference() 48 { 49 return Math.PI * Diameter(); 50 } 51 52 // calculate Circle area 53 public virtual double Area() // declared virtual so it can be overridden 54 { 55 return Math.PI * Math.Pow( Radius, 2 ); // use property 56 } 57 58 // return string representation of Circle4 59 public override string ToString() 60 { 61 // use base reference to return Point string representation 62 return "Center= " + base.ToString() + 63 "; Radius = " + Radius; // use property Radius 64 } 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
32
2009 Pearson Education, Inc. All rights reserved. 32 Slide from ed.1 added by L. Lilien 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 { 10 // main entry point for application 11 static void Main( string[] args ) 12 { 13 // instantiate Circle4 14 Circle4 circle = new Circle4( 37, 43, 2.5 ); 15 16 // get Circle4's initial x-y coordinates and radius 17 string output = "X coordinate is " + circle.X + "\n" + 18 "Y coordinate is " + circle.Y + "\n" + 19 "Radius is " + circle.Radius; 20 21 // set Circle4's x-y coordinates and radius to new values // via properties: X, Y, Radius -- not via private: x, y, radius 22 circle.X = 2; 23 circle.Y = 2; 24 circle.Radius = 4.25; 25 26 // display Circle4's string representation 27 output += "\n\n" + 28 "The new location and radius of circle are " + 29 "\n" + circle + "\n"; 30 31 // display Circle4's Diameter 32 output += "Diameter is " + 33 String.Format( "{0:F}", circle.Diameter() ) + "\n"; 34 Change coordinates and radius of Circle4 object Implicit call to Circle4’s ToString method Call Circle’s Diameter method for output Part 1 of Output :
33
2009 Pearson Education, Inc. All rights reserved. 33 Slide from ed.1 added by L. Lilien 35 // display Circle4's Circumference 36 output += "Circumference is " + 37 String.Format( "{0:F}", circle.Circumference() ) + "\n"; 38 39 // display Circle4's Area 40 output += "Area is " + 41 String.Format( "{0:F}", circle.Area() ); 42 43 MessageBox.Show( output, "Demonstrating Class Circle4" ); 44 45 } // 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
34
2009 Pearson Education, Inc. All rights reserved. 34 Slide added by L. Lilien Self-evaluation Exercise 2 Run the C# project including: Point3.cs / Circle4.cs / CircleTest4.cs Hints: 1)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). 2)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).
35
2009 Pearson Education, Inc. All rights reserved. 35 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 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.
36
2009 Pearson Education, Inc. All rights reserved. 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
2009 Pearson Education, Inc. All rights reserved. 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
2009 Pearson Education, Inc. All rights reserved. 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
2009 Pearson Education, Inc. All rights reserved. 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
2009 Pearson Education, Inc. All rights reserved. 40 Object (namespace: System) ComissionEmployee (CE) From Fig. 11.4 private fN, lN, sSN, gS, cR implicit inheritance Slide added by L. Lilien NAME ABBREAVIATIONS (cf. p.502/ed.3) fN = firstName lN = lastName sSN = socialSecurityNumber gS = grossSales cR = comissionRate
41
2009 Pearson Education, Inc. All rights reserved. 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
2009 Pearson Education, Inc. All rights reserved. 42 Outline Commission Employee.cs (2 of 3)
43
2009 Pearson Education, Inc. All rights reserved. 43 Outline Commission Employee.cs (3 of 3 )
44
2009 Pearson Education, Inc. All rights reserved. 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
2009 Pearson Education, Inc. All rights reserved. 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
2009 Pearson Education, Inc. All rights reserved. 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
2009 Pearson Education, Inc. All rights reserved. 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
2009 Pearson Education, Inc. All rights reserved. 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
2009 Pearson Education, Inc. All rights reserved. 49 11.4 Relationship between Base Classes and Derived Classes (Cont.) Let’s tests class CommissionEmployee
50
2009 Pearson Education, Inc. All rights reserved. 50 Outline Commission EmployeeTest.cs (1 of 2)
51
2009 Pearson Education, Inc. All rights reserved. 51 Output for testing class CommissionEmployee Outline Commission EmployeeTest.cs (2 of 2)
52
2009 Pearson Education, Inc. All rights reserved. 52 Slide added by L. Lilien 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).
53
2009 Pearson Education, Inc. All rights reserved. 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
2009 Pearson Education, Inc. All rights reserved. 54 Object (namespace: System) ComissionEmployee (CE) From Fig.11.4 private fN, lN, sSN, gS, cR implicit inheritance Slide added by L. Lilien NAME ABBREAVIATIONS fN = firstName lN = lastName sSN = socialSecurityNumber gS = grossSales cR = comissionRate bS = baseSalary BasePlusComissionEmployee (BPCE) From Fig.11.6 private fN, lN, sSN, gS, cR, bS
55
2009 Pearson Education, Inc. All rights reserved. 55 Outline BasePlus Commission Employee.cs (1 of 4)
56
2009 Pearson Education, Inc. All rights reserved. 56 Outline BasePlus Commission Employee.cs (2 of 4)
57
2009 Pearson Education, Inc. All rights reserved. 57 Outline BasePlus Commission Employee.cs (3 of 4)
58
2009 Pearson Education, Inc. All rights reserved. 58 Outline BasePlus Commission Employee.cs (4 of 4 )
59
2009 Pearson Education, Inc. All rights reserved. 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
2009 Pearson Education, Inc. All rights reserved. 60 11.4 Relationship between Base Classes and Derived Classes (Cont.) Testing class BasePlusCommissionEmployee
61
2009 Pearson Education, Inc. All rights reserved. 61 Outline BasePlusCommission EmployeeTest.cs (1 of 2)
62
2009 Pearson Education, Inc. All rights reserved. 62 Output for testing class BasePlusCommissionEmployee. Outline BasePlusCommission EmployeeTest.cs (2of 2)
63
2009 Pearson Education, Inc. All rights reserved. 63 Slide added by L. Lilien 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)
64
2009 Pearson Education, Inc. All rights reserved. 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
2009 Pearson Education, Inc. All rights reserved. 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
2009 Pearson Education, Inc. All rights reserved. 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
2009 Pearson Education, Inc. All rights reserved. 67 Object (namespace: System) ComissionEmployee (CE) From Fig.11.4 private fN, lN, sSN, gS, cR public decimal Earnings() implicit inheritance Slide added by L. Lilien NAME ABBREAVIATIONS (cf. p.502/ed.3) fN = firstName lN = lastName sSN = socialSecurityNumber gS = grossSales cR = comissionRate bS = baseSalary 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 explicit inheritance
68
2009 Pearson Education, Inc. All rights reserved. 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.
69
2009 Pearson Education, Inc. All rights reserved. 69 Outline BasePlusCommission Employee.cs (2 of 2 )
70
2009 Pearson Education, Inc. All rights reserved. 70 Slide added by L. Lilien 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.
71
2009 Pearson Education, Inc. All rights reserved. 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
2009 Pearson Education, Inc. All rights reserved. 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
2009 Pearson Education, Inc. All rights reserved. 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. 11.4 is: public virtual decimal Earnings() (instead of: public decimal Earnings() ) We have now the following situation: (next slide)
74
2009 Pearson Education, Inc. All rights reserved. 74 Object (namespace: System) ComissionEmployee (CE) From updated Fig.11.4 (Note 1) private fN, lN, sSN, gS, cR public virtual decimal Earnings() implicit inheritance Slide added by L. Lilien NAME ABBREAVIATIONS (cf. p.502/ed.3) fN = firstName lN = lastName sSN = socialSecurityNumber gS = grossSales cR = comissionRate bS = baseSalary BasePlusComissionEmployee (BPCE) From Fig. 11.8 private bS public override decimal Earnings() explicit inheritance Note 1: The Update changed line 78 in Fig.11.4 to: public virtual decimal Earnings()
75
2009 Pearson Education, Inc. All rights reserved. 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
2009 Pearson Education, Inc. All rights reserved. 76 Slide added by L. Lilien Self-evaluation Exercise 7 Run the C# project (with class inheritance) including: CommissionEmployee (from Fig. 11.4 - 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.
77
2009 Pearson Education, Inc. All rights reserved. 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
2009 Pearson Education, Inc. All rights reserved. 78 Object (namespace: System) ComissionEmployee2 (CE2) From Fig.11.10 protected fN, lN, sSN, gS, cR public virtual decimal Earnings() Slide added by L. Lilien NAME ABBREAVIATIONS fN = firstNamelN = lastName sSN = socialSecurityNumbergS = grossSales cR = comissionRate bS = baseSalary implicit inheritance explicit inheritance ComissionEmployee (CE) From updated Fig. 11.4 private fN, lN, sSN, gS, cR public 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
79
2009 Pearson Education, Inc. All rights reserved. 79 Outline Commission Employee.cs ( 1 of 3)
80
2009 Pearson Education, Inc. All rights reserved. 80 Outline Commission Employee.cs ( 2 of 3)
81
2009 Pearson Education, Inc. All rights reserved. 81 Outline Commission Employee.cs ( 3 of 3) We declare the Earnings method as virtual so that BasePlusCommissionEmployee can override this method.
82
2009 Pearson Education, Inc. All rights reserved. 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
2009 Pearson Education, Inc. All rights reserved. 83 Object (namespace: System) ComissionEmployee2 (CE2) From Fig.11.10 protected fN, lN, sSN, gS, cR public virtual decimal Earnings() Slide added by L. Lilien NAME ABBREAVIATIONS fN = firstNamelN = lastName sSN = socialSecurityNumbergS = grossSales cR = comissionRatebS = baseSalary (cf. p.517/ed.3) BasePlusComissionEmployee (BPCE) From Fig.11.11 private bS public override decimal Earnings() implicit inheritance explicit inheritance ComissionEmployee (CE) From updated Fig. 11.4 private fN, lN, sSN, gS, cR public 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
84
2009 Pearson Education, Inc. All rights reserved. 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
2009 Pearson Education, Inc. All rights reserved. 85 Outline BasePlusCommissi onEmployee.cs ( 2 of 2 )
86
2009 Pearson Education, Inc. All rights reserved. 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
2009 Pearson Education, Inc. All rights reserved. 87 Outline BasePlusCommissio nEmployee.cs ( 1 of 3 ) NOTE: Incorrect name. Should be: BasePlusCommissionEmployeeTest
88
2009 Pearson Education, Inc. All rights reserved. 88 Outline BasePlusCommissio nEmployee.cs ( 2 of 3 ) Output for the testing class BasePlusCommissionEmployee. (Part 3 of 3.)
89
2009 Pearson Education, Inc. All rights reserved. 89 Slide added by L. Lilien 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. 11.12) (if necessary, see hints for previous self-evaluation exercises) See that you get the correct output as shown on the previous slide.
90
2009 Pearson Education, Inc. All rights reserved. 90 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. 11.4 Relationship between Base Classes and Derived Classes (Cont.)
91
2009 Pearson Education, Inc. All rights reserved. 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
2009 Pearson Education, Inc. All rights reserved. 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
2009 Pearson Education, Inc. All rights reserved. 93 Object (namespace: System) Slide added by L. Lilien NAME ABBREAVIATIONS fN = firstNamelN = lastName sSN = socialSecurityNumbergS = grossSales cR = comissionRatebS = baseSalary (cf. p.517/ed.3) implicit inheritance explicit inheritance ComissionEmployee (CE) From Fig.11.13 private fN, lN, sSN, gS, cR public virtual decimal Earnings() CE code shown below (Fig. 11.13, p.520). NOTE: This CE is similar to CE of Fig.11.4, p.502 – BUT it is: a)not using explicit “ : object ” in Line 3, b)having “ virtual ” in Line 78. c)Earnings method accesses instance variables via properties, not directly, in Line 80
94
2009 Pearson Education, Inc. All rights reserved. 94 Outline Commission Employee.cs ( 1 of 3 )
95
2009 Pearson Education, Inc. All rights reserved. 95 Outline Commission Employee.cs ( 2 of 3 )
96
2009 Pearson Education, Inc. All rights reserved. 96 Outline Commission Employee.cs ( 3 of 3 ) Use the class’s properties to obtain the values of its instance variables.
97
2009 Pearson Education, Inc. All rights reserved. 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
2009 Pearson Education, Inc. All rights reserved. 98 Object (namespace: System) Slide added by L. Lilien NAME ABBREAVIATIONS fN = firstNamelN = lastName sSN = socialSecurityNumbergS = grossSales cR = comissionRatebS = baseSalary (cf. p.517/ed.3) implicit inheritance explicit inheritance 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() BPCE code shown below (Fig. 11.14, p.522). NOTE: This BPCE is different than BPCE of Fig.11.11, p.517. Differences: a)one more comment line (4 not 3) b)inheriting from the above CE not from CE2 (Line 5) c)Earnings() does not access baseSalary instance variable directly but uses BaseSalary property (Line 35) d)Earnings() does not access comissionRate and grossSales instance variables directly but calls base.Earnings() that accesses them (via their properties) (Line 35) e)ToString() does not use 5 base class properties directly but calls base.ToString() (Line 42)
99
2009 Pearson Education, Inc. All rights reserved. 99 Outline BasePlusCommissio nEmployee.cs ( 1 of 2 )
100
2009 Pearson Education, Inc. All rights reserved. 100 Outline BasePlusCommissio nEmployee.cs ( 2 of 2 ) Use CommissionEmployee ’s Earnings method to calculate the commission pay, and add it to the BaseSalary. Use CommissionEmployee ’s ToString method to display BasePlusCommissionEmployee.
101
2009 Pearson Education, Inc. All rights reserved. 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
2009 Pearson Education, Inc. All rights reserved. 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
2009 Pearson Education, Inc. All rights reserved. 103 Outline BasePlusCommissio nEmployeeTest.cs ( 1 of 2 )
104
2009 Pearson Education, Inc. All rights reserved. 104 Output for testing class BasePlusCommissionEmployee. Outline BasePlusCommissio nEmployeeTest.cs ( 2 of 2 )
105
2009 Pearson Education, Inc. All rights reserved. 105 Slide added by L. Lilien 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. 11.15) (if necessary, see hints for previous self-evaluation exercises) See that you get the correct output as shown on the previous slide.
106
2009 Pearson Education, Inc. All rights reserved. 106 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 11.4 Relationship between Base Classes and Derived Classes (Cont.)
107
2009 Pearson Education, Inc. All rights reserved. 107 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 11.5 Constructors [and Destructors] in Derived Classes
108
2009 Pearson Education, Inc. All rights reserved. 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
2009 Pearson Education, Inc. All rights reserved. 109 Class CommissionEmployee of Fig.11.13 is modified into class CommissionEmployee of Fig.11.16 Modification (highlighted in Fig. 11.16 below) : to output a message when CE’s constructor is invoked This output is for educational purposes —to show how constructors work 11.5 Constructors [and Destructors] in Derived Classes (Cont.)
110
2009 Pearson Education, Inc. All rights reserved. 110 Outline Commission Employee.cs ( 1 of 3 )
111
2009 Pearson Education, Inc. All rights reserved. 111 Outline Commission Employee.cs ( 2 of 3 )
112
2009 Pearson Education, Inc. All rights reserved. 112 Outline Commission Employee.cs ( 3 of 3 )
113
2009 Pearson Education, Inc. All rights reserved. 113 Class BasePlusCommissionEmployee of Fig. 11.14 is modified into class BasePlusCommissionEmployee of Fig. 11.17 Modification (highlighted in Fig. 11.16 below) : to output a message when BPCE’s constructor is invoked Again, this output is for educational purposes—to show how constructors work 11.5 Constructors [and Destructors] in Derived Classes (Cont.)
114
2009 Pearson Education, Inc. All rights reserved. 114 Outline BasePlusCommissio nEmployee.cs ( 1 of 3 )
115
2009 Pearson Education, Inc. All rights reserved. 115 Outline BasePlusCommissio nEmployee.cs ( 3 of 3 )
116
2009 Pearson Education, Inc. All rights reserved. 116 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. 11.5 Constructors [and Destructors] in Derived Classes (Cont.)
117
2009 Pearson Education, Inc. All rights reserved. 117 Outline Constructor Test.cs ( 1 of 3 )
118
2009 Pearson Education, Inc. All rights reserved. 118 Outline Constructor Test.cs ( 2 of 3 ) Top-level class (no explicit class above it in the inheritance hierarchy) – only 1 constructor called for Bob 2 nd -level class (inherits from one explicit class above it in the inheritance hierarchy) – 2 constructors called for Lisa
119
2009 Pearson Education, Inc. All rights reserved. 119 Outline Constructor Test.cs ( 3 of 3 ) 2 nd -level class (inherits from one explicit class above it in the inheritance hierarchy) – 2 constructors called for Mark
120
2009 Pearson Education, Inc. All rights reserved. 120 Cf. p. 448-449 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) ++OPTIONAL++ 11.5 Constructors [and Destructors] in Derived Classes (Cont.)
121
2009 Pearson Education, Inc. All rights reserved. 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
2009 Pearson Education, Inc. All rights reserved. 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
2009 Pearson Education, Inc. All rights reserved. 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 integrity of the base class
124
2009 Pearson Education, Inc. All rights reserved. 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
2009 Pearson Education, Inc. All rights reserved. 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: http://msdn.microsoft.com/en-us/library/system.object_members.aspx 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
2009 Pearson Education, Inc. All rights reserved. 126 Methods of the object class — inherited (directly or indirectly) by all classes 11.7 Class object (Cont.)
127
2009 Pearson Education, Inc. All rights reserved. 127 The End
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.