Java programming notes OBJECT-ORIENTED PROGRAMMING – INHERITANCE
2009 Pearson Education, Inc. All rights reserved. 1 11 Object-Oriented Programming: Inheritance.
-
Upload
willis-sharp -
Category
Documents
-
view
218 -
download
0
Transcript of 2009 Pearson Education, Inc. All rights reserved. 1 11 Object-Oriented Programming: Inheritance.
2009 Pearson Education, Inc. All rights reserved.
2
Say not you know another entirely, till you have divided an inheritance with him.
– Johann Kasper Lavater
This method is to define as the number of a classthe class of all classes similar to the given class.
– Bertrand Russell
Good as it is to inherit a library,it is better to collect one.
– Augustine Birrell
Save base authority from others’ books.– William Shakespeare
2009 Pearson Education, Inc. All rights reserved.
3
OBJECTIVES
In this chapter you will learn: How inheritance promotes software reusability. The concepts of base classes and derived classes. To create a derived class that inherits attributes
and behaviors from a base class. To use access modifier protected to give derived-class
methods access to base-class members. To access base-class members with base. How constructors are used in inheritance hierarchies. The methods of class object, the direct or
indirect base class of all classes.
2009 Pearson Education, Inc. All rights reserved.
4
11.1 Introduction
11.2 Base Classes and Derived Classes
11.3 protected Members
11.4 Relationship between Base Classes and Derived Classes
11.5 Constructors in Derived Classes
11.6 Software Engineering with Inheritance
11.7 Class object
2009 Pearson Education, Inc. All rights reserved.
5
11.1 Introduction
• Inheritance allows a new class to absorb an existing class’s members.
• A derived class normally adds its own fields and methods to represent a more specialized group of objects.
• Inheritance saves time by reusing proven and debugged high-quality software.
2009 Pearson Education, Inc. All rights reserved.
6
11.1 Introduction (Cont.)
• The direct base class is the base class which the derived class explicitly inherits.
• An indirect base class is any class above the direct base class in the class hierarchy.
• The class hierarchy begins with class object.
2009 Pearson Education, Inc. All rights reserved.
7
11.1 Introduction (Cont.)
• The is-a relationship represents inheritance.
• For example, a car is a vehicle, and a truck is a vehicle.
• New classes can inherit from thousands of pre-built classes in class libraries.
2009 Pearson Education, Inc. All rights reserved.
8
11.2 Base Classes and Derived Classes
• Figure 11.1 lists several simple examples of base classes and derived classes.
• Note that base classes are “more general,” and derived classes are “more specific.”
Base class Derived classes
Student GraduateStudent, UndergraduateStudent
Shape Circle, Triangle, Rectangle
Loan CarLoan, HomeImprovementLoan, MortgageLoan
Employee Faculty, Staff, HourlyWorker, CommissionWorker
BankAccount CheckingAccount, SavingsAccount
Fig. 11.1 | Inheritance examples.
2009 Pearson Education, Inc. All rights reserved.
9
11.2 Base Classes and Derived Classes (Cont.)
• The UML class diagram of Fig. 11.2 shows an inheritance hierarchy representing a university community.
• Each arrow represents an is-a relationship.
Fig. 11.2 | UML class diagram showing an inheritance hierarchyfor university CommunityMembers.
2009 Pearson Education, Inc. All rights reserved.
10
11.2 Base Classes and Derived Classes (Cont.)
• Now consider the Shape inheritance hierarchy in Fig. 11.3.
• We can follow the arrows to identify several is-a relationships.
Fig. 11.3 | UML class diagram showing an inheritance hierarchy for Shapes.
2009 Pearson Education, Inc. All rights reserved.
11
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.
• 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.
2009 Pearson Education, Inc. All rights reserved.
12
11.3 protected Members
• A base class’s private members are inherited by derived classes, but are not directly accessible by derived-class methods and properties.
• A base class’s protected members can be accessed by members of that base class and by members of its derived classes.
• A base class’s protected internal members can be accessed by members of a base class, the derived classes and by any class in the same assembly.
2009 Pearson Education, Inc. All rights reserved.
13
11.3 protected Members (Cont.)
Software Engineering Observation 11.1Properties and methods of a derived class cannot directlyaccess 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.
Software Engineering Observation 11.2
If a derived class can access its base class’s private fields,classes that inherit from that base class could access thefields as well. This would propagate access to what shouldbe private fields, and the benefits of informationhiding would be lost.
2009 Pearson Education, Inc. All rights reserved.
14
1 // Fig. 11.4: CommissionEmployee.cs
2 // CommissionEmployee class represents a commission employee.
3 public class CommissionEmployee : object
4 {
5 private string firstName;
6 private string lastName;
7 private string socialSecurityNumber;
8 private decimal grossSales; // gross weekly sales
9 private decimal commissionRate; // commission percentage
10
11 // five-parameter constructor
12 public CommissionEmployee( string first, string last, string ssn,
13 decimal sales, decimal rate )
14 {
15 // implicit call to object constructor occurs here
Fig. 11.4 | CommissionEmployee class represents acommission employee. (Part 1 of 5.)
Outline
CommissionEmployee.cs
(1 of 5 )
• CommissionEmployee (Fig. 11.4) represents anemployee who is paid a percentage of their sales.
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.
2009 Pearson Education, Inc. All rights reserved.
15
16 firstName = first;
17 lastName = last;
18 socialSecurityNumber = ssn;
19 GrossSales = sales; // validate gross sales via property
20 CommissionRate = rate; // validate commission rate via property
21 } // end five-parameter CommissionEmployee constructor
22
23 // read-only property that gets commission employee's first name
24 public string FirstName
25 {
26 get
27 {
28 return firstName;
29 } // end get
30 } // end property FirstName
31
Fig. 11.4 | CommissionEmployee class represents acommission employee. (Part 2 of 5.)
Outline
CommissionEmployee.cs
(2 of 5 )
2009 Pearson Education, Inc. All rights reserved.
16
32 // read-only property that gets commission employee's last name
33 public string LastName
34 {
35 get
36 {
37 return lastName;
38 } // end get
39 } // end property LastName
40
41 // read-only property that gets
42 // commission employee's social security number
43 public string SocialSecurityNumber
44 {
Fig. 11.4 | CommissionEmployee class represents acommission employee. (Part 3 of 5.)
Outline
CommissionEmployee.cs
(3 of 5 )
2009 Pearson Education, Inc. All rights reserved.
17
45 get
46 {
47 return socialSecurityNumber;
48 } // end get
49 } // end property SocialSecurityNumber
50
51 // property that gets and sets commission employee's gross sales
52 public decimal GrossSales
53 {
54 get
55 {
56 return grossSales;
57 } // end get
58 set
59 {
60 grossSales = ( value < 0 ) ? 0 : value;
61 } // end set
62 } // end property GrossSales
63
64 // property that gets and sets commission employee's commission rate
65 public decimal CommissionRate
66 {
67 get
Fig. 11.4 | CommissionEmployee class represents acommission employee. (Part 4 of 5.)
Outline
CommissionEmployee.cs
(4 of 5 )
2009 Pearson Education, Inc. All rights reserved.
18
68 {
69 return commissionRate;
70 } // end get
71 set
72 {
73 commissionRate = ( value > 0 && value < 1 ) ? value : 0;
74 } // end set
75 } // end property CommissionRate
76
77 // calculate commission employee's pay
78 public decimal Earnings()
79 {
80 return commissionRate * grossSales;
81 } // end method Earnings
82
83 // return string representation of CommissionEmployee object
84 public override string ToString()
85 {
86 return string.Format(
87 "{0}: {1} {2}\n{3}: {4}\n{5}: {6:C}\n{7}: {8:F2}",
88 "commission employee", FirstName, LastName,
89 "social security number", SocialSecurityNumber,
90 "gross sales", GrossSales, "commission rate", CommissionRate );
91 } // end method ToString
92 } // end class CommissionEmployee
Fig. 11.4 | CommissionEmployee class represents acommission employee. (Part 5 of 5.)
Outline
CommissionEmployee.cs
(5 of 5 )
2009 Pearson Education, Inc. All rights reserved.
19
11.4 Relationship between Base Classes and Derived Classes (Cont.)
• A colon (:) followed a class name at the end of the class declaration header indicates that the class extends the classto 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.
Software Engineering Observation 11.3
The compiler sets the base class of a class to object when the class declaration does not explicitly extend a base class.
2009 Pearson Education, Inc. All rights reserved.
20
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.
• Either explicitly or implicitly, a call to the base-class constructor is made.
• Class object’s default (empty) constructor does nothing.
• Note that even if a class does not have constructors, the default constructor will call the base class’s default or parameterless constructor.
2009 Pearson Education, Inc. All rights reserved.
21
11.4 Relationship between Base Classes and Derived Classes (Cont.)
• Method ToString is special—it is one of the methods that every class inherits directly or indirectly from class object.
• Method ToString returns a string representing an object.
• 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 a method with keyword override.
• The method must have the same signature (method name, number of parameters and parameter types) and return type as the base-class method.
2009 Pearson Education, Inc. All rights reserved.
22
11.4 Relationship between Base Classes and Derived Classes (Cont.)
Common Programming Error 11.1It is a compilation error to override a method with a different access modifier. 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.
2009 Pearson Education, Inc. All rights reserved.
23
1 // Fig. 11.5: CommissionEmployeeTest.cs
2 // Testing class CommissionEmployee.
3 using System;
4
5 public class CommissionEmployeeTest
6 {
7 public static void Main( string[] args )
8 {
9 // instantiate CommissionEmployee object
10 CommissionEmployee employee = new CommissionEmployee( "Sue",
11 "Jones", "222-22-2222", 10000.00M, .06M );
12
13 // display commission-employee data
14 Console.WriteLine(
15 "Employee information obtained by properties and methods: \n" );
16 Console.WriteLine( "First name is {0}", employee.FirstName );
17 Console.WriteLine( "Last name is {0}", employee.LastName );
18 Console.WriteLine( "Social security number is {0}",
• Figure 11.5 tests class CommissionEmployee.
Fig. 11.5 | Testing class CommissionEmployee. (Part 1 of 3.)
Outline
CommissionEmployeeTest.cs
(1 of 3 )
2009 Pearson Education, Inc. All rights reserved.
24
19 employee.SocialSecurityNumber );
20 Console.WriteLine( "Gross sales are {0:C}", employee.GrossSales );
21 Console.WriteLine( "Commission rate is {0:F2}",
22 employee.CommissionRate );
23 Console.WriteLine( "Earnings are {0:C}", employee.Earnings() );
24
25 employee.GrossSales = 5000.00M; // set gross sales
26 employee.CommissionRate = .1M; // set commission rate
27
28 Console.WriteLine( "\n{0}:\n\n{1}",
29 "Updated employee information obtained by ToString", employee );
30 Console.WriteLine( "earnings: {0:C}", employee.Earnings() );
31 } // end Main
32 } // end class CommissionEmployeeTest
Fig. 11.5 | Testing class CommissionEmployee. (Part 2 of 3.)
Outline
CommissionEmployeeTest.cs
(2 of 3 )
2009 Pearson Education, Inc. All rights reserved.
25
Employee information obtained by properties and methods:
First name is Sue
Last name is Jones
Social security number is 222-22-2222
Gross sales are $10,000.00
Commission rate is 0.06
Earnings are $600.00
Updated employee information obtained by ToString:
commission employee: Sue Jones
social security number: 222-22-2222
gross sales: $5,000.00
commission rate: 0.10
earnings: $500.00
Fig. 11.5 | Testing class CommissionEmployee. (Part 3 of 3.)
Outline
CommissionEmployeeTest.cs
(3 of 3 )
2009 Pearson Education, Inc. All rights reserved.
26
1 // Fig. 11.6: BasePlusCommissionEmployee.cs
2 // BasePlusCommissionEmployee class represents an employee that receives
3 // a base salary in addition to a commission.
4 public class BasePlusCommissionEmployee
5 {
6 private string firstName;
7 private string lastName;
8 private string socialSecurityNumber;
9 private decimal grossSales; // gross weekly sales
10 private decimal commissionRate; // commission percentage
11 private decimal baseSalary; // base salary per week
12
13 // six-parameter constructor
14 public BasePlusCommissionEmployee( string first, string last,
15 string ssn, decimal sales, decimal rate, decimal salary )
16 {
• We now declare and test a separate class BasePlusCommissionEmployee (Fig. 11.6),
Fig. 11.6 | BasePlusCommissionEmployee class represents an employeethat receives a base salary in addition to a commission. (Part 1 of 6.)
Outline
BasePlusCommissionEmployee.cs
(1 of 6 )
2009 Pearson Education, Inc. All rights reserved.
27
17 // implicit call to object constructor occurs here
18 firstName = first;
19 lastName = last;
20 socialSecurityNumber = ssn;
21 GrossSales = sales; // validate gross sales via property
22 CommissionRate = rate; // validate commission rate via property
23 BaseSalary = salary; // validate base salary via property
24 } // end six-parameter BasePlusCommissionEmployee constructor
25
26 // read-only property that gets
27 // base-salaried commission employee's first name
28 public string FirstName
29 {
30 get
31 {
32 return firstName;
33 } // end get
34 } // end property FirstName
35
Fig. 11.6 | BasePlusCommissionEmployee class represents an employeethat receives a base salary in addition to a commission. (Part 2 of 6.)
Outline
BasePlusCommissionEmployee.cs
(2 of 6 )
2009 Pearson Education, Inc. All rights reserved.
2836 // read-only property that gets
37 // base-salaried commission employee's last name
38 public string LastName
39 {
40 get
41 {
42 return lastName;
43 } // end get
44 } // end property LastName
45
46 // read-only property that gets
47 // base-salaried commission employee's social security number
48 public string SocialSecurityNumber
49 {
50 get
51 {
52 return socialSecurityNumber;
53 } // end get
54 } // end property SocialSecurityNumber
55
56 // property that gets and sets
57 // base-salaried commission employee's gross sales
58 public decimal GrossSales
59 {
60 get
Fig. 11.6 | BasePlusCommissionEmployee class represents an employeethat receives a base salary in addition to a commission. (Part 3 of 6.)
Outline
BasePlusCommissionEmployee.cs
(3 of 6 )
2009 Pearson Education, Inc. All rights reserved.
29
61 {
62 return grossSales;
63 } // end get
64 set
65 {
66 grossSales = ( value < 0 ) ? 0 : value;
67 } // end set
68 } // end property GrossSales
69
70 // property that gets and sets
71 // base-salaried commission employee's commission rate
72 public decimal CommissionRate
73 {
74 get
75 {
76 return commissionRate;
77 } // end get
78 set
79 {
80 commissionRate = ( value > 0 && value < 1 ) ? value : 0;
Fig. 11.6 | BasePlusCommissionEmployee class represents an employeethat receives a base salary in addition to a commission. (Part 4 of 6.)
Outline
BasePlusCommissionEmployee.cs
(4 of 6 )
2009 Pearson Education, Inc. All rights reserved.
30
81 } // end set
82 } // end property CommissionRate
83
84 // property that gets and sets
85 // base-salaried commission employee's base salary
86 public decimal BaseSalary
87 {
88 get
89 {
90 return baseSalary;
91 } // end get
92 set
93 {
Fig. 11.6 | BasePlusCommissionEmployee class represents an employeethat receives a base salary in addition to a commission. (Part 5 of 6.)
Outline
BasePlusCommissionEmployee.cs
(5 of 6 )
2009 Pearson Education, Inc. All rights reserved.
31
94 baseSalary = ( value < 0 ) ? 0 : value;
95 } // end set
96 } // end property BaseSalary
97
98 // calculate earnings
99 public decimal Earnings()
100 {
101 return BaseSalary + ( CommissionRate * GrossSales );
102 } // end method earnings
103
104 // return string representation of BasePlusCommissionEmployee
105 public override string ToString()
106 {
107 return string.Format(
108 "{0}: {1} {2}\n{3}: {4}\n{5}: {6:C}\n{7}: {8:F2}\n{9}: {10:C}",
109 "base-salaried commission employee", FirstName, LastName,
110 "social security number", SocialSecurityNumber,
111 "gross sales", GrossSales, "commission rate", CommissionRate,
112 "base salary", BaseSalary );
113 } // end method ToString
114 } // end class BasePlusCommissionEmployee
Fig. 11.6 | BasePlusCommissionEmployee class represents an employeethat receives a base salary in addition to a commission. (Part 6 of 6.)
Outline
BasePlusCommissionEmployee.cs
(6 of 6 )
2009 Pearson Education, Inc. All rights reserved.
32
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.
2009 Pearson Education, Inc. All rights reserved.
33
1 // Fig. 11.7: BasePlusCommissionEmployeeTest.cs
2 // Testing class BasePlusCommissionEmployee.
3 using System;
4
5 public class BasePlusCommissionEmployeeTest
6 {
7 public static void Main( string[] args )
8 {
9 // instantiate BasePlusCommissionEmployee object
10 BasePlusCommissionEmployee employee =
11 new BasePlusCommissionEmployee( "Bob", "Lewis",
12 "333-33-3333", 5000.00M, .04M, 300.00M );
13
14 // display base-salaried commission-employee data
15 Console.WriteLine(
16 "Employee information obtained by properties and methods: \n" );
17 Console.WriteLine( "First name is {0}", employee.FirstName );
18 Console.WriteLine( "Last name is {0}", employee.LastName );
• Figure 11.7 tests class BasePlusCommissionEmployee.
Fig. 11.7 | Testing class BasePlusCommissionEmployee. (Part 1 of 3.)
Outline
BasePlusCommissionEmployeeTest.cs
(1 of 3 )
2009 Pearson Education, Inc. All rights reserved.
34
19 Console.WriteLine( "Social security number is {0}",
20 employee.SocialSecurityNumber );
21 Console.WriteLine( "Gross sales are {0:C}", employee.GrossSales );
22 Console.WriteLine( "Commission rate is {0:F2}",
23 employee.CommissionRate );
24 Console.WriteLine( "Earnings are {0:C}", employee.Earnings() );
25 Console.WriteLine( "Base salary is {0:C}", employee.BaseSalary );
26
27 employee.BaseSalary = 1000.00M; // set base salary
28
29 Console.WriteLine( "\n{0}:\n\n{1}",
30 "Updated employee information obtained by ToString", employee );
31 Console.WriteLine( "earnings: {0:C}", employee.Earnings() );
32 } // end Main
33 } // end class BasePlusCommissionEmployeeTest
Fig. 11.7 | Testing class BasePlusCommissionEmployee. (Part 2 of 3.)
Outline
BasePlusCommissionEmployeeTest.cs
(2 of 3 )
2009 Pearson Education, Inc. All rights reserved.
35
Employee information obtained by properties and methods: First name is Bob Last name is Lewis Social security number is 333-33-3333 Gross sales are $5,000.00 Commission rate is 0.04 Earnings are $500.00 Base salary is $300.00 Updated employee information obtained by ToString: base-salaried commission employee: Bob Lewis social security number: 333-33-3333 gross sales: $5,000.00 commission rate: 0.04 base salary: $1,000.00 earnings: $1,200.00
Fig. 11.7 | Testing class BasePlusCommissionEmployee. (Part 3 of 3.)
Outline
BasePlusCommissionEmployeeTest.cs
(3 of 3 )
2009 Pearson Education, Inc. All rights reserved.
36
11.4 Relationship between Base Classes and Derived Classes (Cont.)
• Much of the code for BasePlusCommissionEmployeeis similar to the code for CommissionEmployee.
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” approach.
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.
2009 Pearson Education, Inc. All rights reserved.
37
1 // Fig. 11.8: BasePlusCommissionEmployee.cs
2 // BasePlusCommissionEmployee inherits from class CommissionEmployee.
3 public class BasePlusCommissionEmployee : CommissionEmployee
4 {
5 private decimal baseSalary; // base salary per week
6
7 // six-parameter derived-class constructor
8 // with call to base class CommissionEmployee constructor
9 public BasePlusCommissionEmployee( string first, string last,
10 string ssn, decimal sales, decimal rate, decimal salary )
11 : base( first, last, ssn, sales, rate )
12 {
13 BaseSalary = salary; // validate base salary via property
14 } // end six-parameter BasePlusCommissionEmployee constructor
15
• Now we declare class BasePlusCommissionEmployee (Fig. 11.8), which extends class CommissionEmployee (Fig. 11.4).
Fig. 11.8 | BasePlusCommissionEmployee inherits from classCommissionEmployee. (Part 1 of 3.)
Outline
BasePlusCommissionEmployee.cs
(1 of 3 )
Class BasePlusCommissionEmployeehas an additional instance variable baseSalary.
Invoke the CommissionEmployee’s five-parameter constructor using a constructor initializer.
2009 Pearson Education, Inc. All rights reserved.
38
16 // property that gets and sets
17 // base-salaried commission employee's base salary
18 public decimal BaseSalary
19 {
20 get
21 {
22 return baseSalary;
23 } // end get
24 set
25 {
26 baseSalary = ( value < 0 ) ? 0 : value;
27 } // end set
28 } // end property BaseSalary
29
30 // calculate earnings
31 public override decimal Earnings()
32 {
Fig. 11.8 | BasePlusCommissionEmployee inherits from classCommissionEmployee. (Part 2 of 3.)
Outline
BasePlusCommissionEmployee.cs
(2 of 3 )
2009 Pearson Education, Inc. All rights reserved.
39
33 // not allowed: commissionRate and grossSales private in base class
34 return baseSalary + ( commissionRate * grossSales );
35 } // end method Earnings
36
37 // return string representation of BasePlusCommissionEmployee
38 public override string ToString()
39 {
40 // not allowed: attempts to access private base-class members
41 return string.Format(
42 "{0}: {1} {2}\n{3}: {4}\n{5}: {6:C}\n{7}: {8:F2}\n{9}: {10:C}",
43 "base-salaried commission employee", firstName, lastName,
44 "social security number", socialSecurityNumber,
45 "gross sales", grossSales, "commission rate", commissionRate,
46 "base salary", baseSalary );
47 } // end method ToString
48 } // end class BasePlusCommissionEmployee
Fig. 11.8 | BasePlusCommissionEmployee inherits from classCommissionEmployee. (Part 3 of 3.)
Outline
BasePlusCommissionEmployee.cs
(3 of 3 )
2009 Pearson Education, Inc. All rights reserved.
40
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.
Common Programming Error 11.2A 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.
2009 Pearson Education, Inc. All rights reserved.
41
11.4 Relationship between Base Classes and Derived Classes (Cont.)
• The virtual and abstract keywords indicate that a base-class method can 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 virtual.
• We need to declare CommissionEmployee’s Earnings method virtual.
2009 Pearson Education, Inc. All rights reserved.
42
11.4 Relationship between Base Classes and Derived Classes (Cont.)
• The compiler generates additional errors because base class CommissionEmployee’s instance variables are private.
• The errors can be prevented by using the public properties inherited from class CommissionEmployee.
Fig. 11.9 | Compilation errors generated by BasePlusCommissionEmployee (Fig. 11.8) after declaring the Earnings method in Fig. 11.4 with keyword virtual.
2009 Pearson Education, Inc. All rights reserved.
43
1 // Fig. 11.10: CommissionEmployee.cs
2 // CommissionEmployee with protected instance variables.
3 public class CommissionEmployee
4 {
5 protected string firstName;
6 protected string lastName;
7 protected string socialSecurityNumber;
8 protected decimal grossSales; // gross weekly sales
9 protected decimal commissionRate; // commission percentage
10
11 // five-parameter constructor
12 public CommissionEmployee( string first, string last, string ssn,
13 decimal sales, decimal rate )
14 {
• Class CommissionEmployee (Fig. 11.10) is modified to declare its instance variables as protected rather than private (Fig. 11.10).
Fig. 11.10 | CommissionEmployee with protected instance variables. (Part 1 of 5.)
Outline
CommissionEmployee.cs
( 1 of 5 )
2009 Pearson Education, Inc. All rights reserved.
44
15 // implicit call to object constructor occurs here
16 firstName = first;
17 lastName = last;
18 socialSecurityNumber = ssn;
19 GrossSales = sales; // validate gross sales via property
20 CommissionRate = rate; // validate commission rate via property
21 } // end five-parameter CommissionEmployee constructor
22
23 // read-only property that gets commission employee's first name
24 public string FirstName
25 {
26 get
27 {
28 return firstName;
29 } // end get
30 } // end property FirstName
31
32 // read-only property that gets commission employee's last name
33 public string LastName
34 {
35 get
36 {
Fig. 11.10 | CommissionEmployee with protected instance variables. (Part 2 of 5.)
Outline
CommissionEmployee.cs
( 2 of 5 )
2009 Pearson Education, Inc. All rights reserved.
45
37 return lastName;
38 } // end get
39 } // end property LastName
40
41 // read-only property that gets
42 // commission employee's social security number
43 public string SocialSecurityNumber
44 {
45 get
46 {
47 return socialSecurityNumber;
48 } // end get
49 } // end property SocialSecurityNumber
50
51 // property that gets and sets commission employee's gross sales
52 public decimal GrossSales
53 {
54 get
55 {
56 return grossSales;
57 } // end get
58 set
59 {
Fig. 11.10 | CommissionEmployee with protected instance variables. (Part 3 of 5.)
Outline
CommissionEmployee.cs
( 3 of 5 )
2009 Pearson Education, Inc. All rights reserved.
4660 grossSales = ( value < 0 ) ? 0 : value;
61 } // end set
62 } // end property GrossSales
63
64 // property that gets and sets commission employee's commission rate
65 public decimal CommissionRate
66 {
67 get
68 {
69 return commissionRate;
70 } // end get
71 set
72 {
73 commissionRate = ( value > 0 && value < 1 ) ? value : 0;
74 } // end set
75 } // end property CommissionRate
76
77 // calculate commission employee's pay
78 public virtual decimal Earnings()
79 {
80 return commissionRate * grossSales;
81 } // end method Earnings
82
83 // return string representation of CommissionEmployee object
84 public override string ToString()
85 {
Fig. 11.10 | CommissionEmployee with protected instance variables. (Part 4 of 5.)
Outline
CommissionEmployee.cs
( 4 of 5 )
2009 Pearson Education, Inc. All rights reserved.
47
86 return string.Format(
87 "{0}: {1} {2}\n{3}: {4}\n{5}: {6:C}\n{7}: {8:F2}",
88 "commission employee", firstName, lastName,
89 "social security number", socialSecurityNumber,
90 "gross sales", grossSales, "commission rate", commissionRate );
91 } // end method ToString
92 } // end class CommissionEmployee
Fig. 11.10 | CommissionEmployee with protected instance variables. (Part 5 of 5.)
• We also declare the Earnings method virtual in line 78 so that BasePlusCommissionEmployee can override the method.
Outline
CommissionEmployee.cs
( 5 of 5 )
2009 Pearson Education, Inc. All rights reserved.
48
1 // Fig. 11.11: BasePlusCommissionEmployee.cs
2 // BasePlusCommissionEmployee inherits from CommissionEmployee and has
3 // access to CommissionEmployee's protected members.
4 public class BasePlusCommissionEmployee : CommissionEmployee2
5 {
6 private decimal baseSalary; // base salary per week
7
8 // six-parameter derived-class constructor
9 // with call to base class CommissionEmployee constructor
10 public BasePlusCommissionEmployee( string first, string last,
11 string ssn, decimal sales, decimal rate, decimal salary )
12 : base( first, last, ssn, sales, rate )
13 {
14 BaseSalary = salary; // validate base salary via property
15 } // end six-parameter BasePlusCommissionEmployee constructor
16
• Class BasePlusCommissionEmployee (Fig. 11.11) is modified to extend CommissionEmployee.
• The instance variables are now protected members,so the compiler does not generate errors.
Fig. 11.11 | BasePlusCommissionEmployee inherits from CommissionEmployeeand has access to CommissionEmployee's protected members. (Part 1 of 3.)
Outline
BasePlusCommissionEmployee.cs
( 1 of 3 )
BasePlusCommissionEmployee’s six-parameter constructor calls class CommissionEmployee’s five-parameter constructor with a constructor initializer.
2009 Pearson Education, Inc. All rights reserved.
49
17 // property that gets and sets
18 // base-salaried commission employee's base salary
19 public decimal BaseSalary
20 {
21 get
22 {
23 return baseSalary;
24 } // end get
25 set
26 {
27 baseSalary = ( value < 0 ) ? 0 : value;
28 } // end set
29 } // end property BaseSalary
30
31 // calculate earnings
32 public override decimal Earnings()
33 {
34 return baseSalary + ( commissionRate * grossSales );
35 } // end method Earnings
Fig. 11.11 | BasePlusCommissionEmployee inherits from CommissionEmployeeand has access to CommissionEmployee's protected members. (Part 2 of 3.)
Outline
BasePlusCommissionEmployee.cs
( 2 of 3 )
2009 Pearson Education, Inc. All rights reserved.
50
36
37 // return string representation of BasePlusCommissionEmployee
38 public override string ToString()
39 {
40 return string.Format(
41 "{0}: {1} {2}\n{3}: {4}\n{5}: {6:C}\n{7}: {8:F2}\n{9}: {10:C}",
42 "base-salaried commission employee", firstName, lastName,
43 "social security number", socialSecurityNumber,
44 "gross sales", grossSales, "commission rate", commissionRate,
45 "base salary", baseSalary );
46 } // end method ToString
47 } // end class BasePlusCommissionEmployee
Fig. 11.11 | BasePlusCommissionEmployee inherits from CommissionEmployeeand has access to CommissionEmployee's protected members. (Part 3 of 3.)
Outline
BasePlusCommissionEmployee.cs
( 3 of 3 )
2009 Pearson Education, Inc. All rights reserved.
51
1 // Fig. 11.12: BasePlusCommissionEmployee.cs
2 // Testing class BasePlusCommissionEmployee.
3 using System;
4
5 public class BasePlusCommissionEmployee
6 {
7 public static void Main( string[] args )
8 {
9 // instantiate BasePlusCommissionEmployee object
10 BasePlusCommissionEmployee basePlusCommissionEmployee =
11 new BasePlusCommissionEmployee( "Bob", "Lewis",
12 "333-33-3333", 5000.00M, .04M, 300.00M );
13
14 // display base-salaried commission-employee data
15 Console.WriteLine(
16 "Employee information obtained by properties and methods: \n" );
• Figure 11.12 tests a BasePlusCommissionEmployee object.
• While the output is identical, there is less code repetition and overall this is a better implementation.
Fig. 11.12 | Testing class BasePlusCommissionEmployee. (Part 1 of 3.)
Outline
BasePlusCommissionEmployee.cs
( 1 of 3 )
2009 Pearson Education, Inc. All rights reserved.
52
17 Console.WriteLine( "First name is {0}",
18 basePlusCommissionEmployee.FirstName );
19 Console.WriteLine( "Last name is {0}",
20 basePlusCommissionEmployee.LastName );
21 Console.WriteLine( "Social security number is {0}",
22 basePlusCommissionEmployee.SocialSecurityNumber );
23 Console.WriteLine( "Gross sales are {0:C}",
24 basePlusCommissionEmployee.GrossSales );
25 Console.WriteLine( "Commission rate is {0:F2}",
26 basePlusCommissionEmployee.CommissionRate );
27 Console.WriteLine( "Earnings are {0:C}",
28 basePlusCommissionEmployee.Earnings() );
29 Console.WriteLine( "Base salary is {0:C}",
30 basePlusCommissionEmployee.BaseSalary );
31
32 basePlusCommissionEmployee.BaseSalary = 1000.00M; // set base salary
33
34 Console.WriteLine( "\n{0}:\n\n{1}",
35 "Updated employee information obtained by ToString",
36 basePlusCommissionEmployee );
37 Console.WriteLine( "earnings: {0:C}",
38 basePlusCommissionEmployee.Earnings() );
39 } // end Main
40 } // end class BasePlusCommissionEmployee
Fig. 11.12 | Testing class BasePlusCommissionEmployee. (Part 2 of 3.)
Outline
BasePlusCommissionEmployee.cs
( 2 of 3 )
2009 Pearson Education, Inc. All rights reserved.
53
Employee information obtained by properties and methods: First name is Bob Last name is Lewis Social security number is 333-33-3333 Gross sales are $5,000.00 Commission rate is 0.04 Earnings are $500.00 Base salary is $300.00 Updated employee information obtained by ToString: base-salaried commission employee: Bob Lewis social security number: 333-33-3333 gross sales: $5,000.00 commission rate: 0.04 base salary: $1,000.00 earnings: $1,200.00
Fig. 11.12 | Testing class BasePlusCommissionEmployee. (Part 3 of 3.)
Outline
BasePlusCommissionEmployee.cs
( 3 of 3 )
2009 Pearson Education, Inc. All rights reserved.
54
11.4 Relationship between Base Classes and Derived Classes (Cont.)
Software Engineering Observation 11.5Declaring base-class instance variables private enables the base-class implementation of these instance variables to change without affecting derived-class implementations.
• Using protected instance variables creates several potential problems.
– The derived-class object can set an inherited variable’s value directly without validity checking.
– Derived-class methods would need to be written to depend on the base class’s data implementation.
• You should be able to change the base-class implementation while still providing the same services to the derived classes.
2009 Pearson Education, Inc. All rights reserved.
55
1 // Fig. 11.13: CommissionEmployee.cs
2 // CommissionEmployee class represents a commission employee.
3 public class CommissionEmployee
4 {
5 private string firstName;
6 private string lastName;
7 private string socialSecurityNumber;
8 private decimal grossSales; // gross weekly sales
9 private decimal commissionRate; // commission percentage
10
11 // five-parameter constructor
12 public CommissionEmployee( string first, string last, string ssn,
13 decimal sales, decimal rate )
14 {
• Class CommissionEmployee (Fig. 11.13) is modified to declare private instance variables and provide public properties.
Fig. 11.13 | CommissionEmployee class represents a commission employee. (Part 1 of 5.)
Outline
CommissionEmployee.cs
( 1 of 5 )
2009 Pearson Education, Inc. All rights reserved.
5615 // implicit call to object constructor occurs here
16 firstName = first;
17 lastName = last;
18 socialSecurityNumber = ssn;
19 GrossSales = sales; // validate gross sales via property
20 CommissionRate = rate; // validate commission rate via property
21 } // end five-parameter CommissionEmployee constructor
22
23 // read-only property that gets commission employee's first name
24 public string FirstName
25 {
26 get
27 {
28 return firstName;
29 } // end get
30 } // end property FirstName
31
32 // read-only property that gets commission employee's last name
33 public string LastName
34 {
35 get
36 {
37 return lastName;
38 } // end get
39 } // end property LastName
40
Fig. 11.13 | CommissionEmployee class represents a commission employee. (Part 2 of 5.)
Outline
CommissionEmployee.cs
( 2 of 5 )
2009 Pearson Education, Inc. All rights reserved.
57
41 // read-only property that gets
42 // commission employee's social security number
43 public string SocialSecurityNumber
44 {
45 get
46 {
47 return socialSecurityNumber;
48 } // end get
49 } // end property SocialSecurityNumber
50
51 // property that gets and sets commission employee's gross sales
52 public decimal GrossSales
53 {
54 get
55 {
56 return grossSales;
57 } // end get
58 set
59 {
60 grossSales = ( value < 0 ) ? 0 : value;
61 } // end set
62 } // end property GrossSales
Fig. 11.13 | CommissionEmployee class represents a commission employee. (Part 3 of 5.)
Outline
CommissionEmployee.cs
( 3 of 5 )
2009 Pearson Education, Inc. All rights reserved.
58
63
64 // property that gets and sets commission employee's commission rate
65 public decimal CommissionRate
66 {
67 get
68 {
69 return commissionRate;
70 } // end get
71 set
72 {
73 commissionRate = ( value > 0 && value < 1 ) ? value : 0;
74 } // end set
75 } // end property CommissionRate
76
77 // calculate commission employee's pay
78 public virtual decimal Earnings()
79 {
80 return CommissionRate * GrossSales;
81 } // end method Earnings
Fig. 11.13 | CommissionEmployee class represents a commission employee. (Part 4 of 5.)
Outline
CommissionEmployee.cs
( 4 of 5 )
Use the class’s properties to obtain the values of its instance variables.
2009 Pearson Education, Inc. All rights reserved.
59
82
83 // return string representation of CommissionEmployee object
84 public override string ToString()
85 {
86 return string.Format(
87 "{0}: {1} {2}\n{3}: {4}\n{5}: {6:C}\n{7}: {8:F2}",
88 "commission employee", FirstName, LastName,
89 "social security number", SocialSecurityNumber,
90 "gross sales", GrossSales, "commission rate", CommissionRate );
91 } // end method ToString
92 } // end class CommissionEmployee
Fig. 11.13 | CommissionEmployee class represents a commission employee. (Part 5 of 5.)
Outline
CommissionEmployee.cs
( 5 of 5 )
2009 Pearson Education, Inc. All rights reserved.
60
1 // Fig. 11.14: BasePlusCommissionEmployee.cs
2 // BasePlusCommissionEmployee inherits from CommissionEmployee and has
3 // access to CommissionEmployee's private data via
4 // its public properties.
5 public class BasePlusCommissionEmployee : CommissionEmployee
6 {
7 private decimal baseSalary; // base salary per week
8
9 // six-parameter derived class constructor
10 // with call to base class CommissionEmployee constructor
11 public BasePlusCommissionEmployee( string first, string last,
12 string ssn, decimal sales, decimal rate, decimal salary )
13 : base( first, last, ssn, sales, rate )
14 {
15 BaseSalary = salary; // validate base salary via property
16 } // end six-parameter BasePlusCommissionEmployee constructor
• Class BasePlusCommissionEmployee (Fig. 11.14) has several changes to its method implementations.
Fig. 11.14 | BasePlusCommissionEmployee inherits from CommissionEmployeeand has access to CommissionEmployee's private data via its public
properties. (Part 1 of 3.)
Outline
BasePlusCommissionEmployee.cs
( 1 of 3 )
2009 Pearson Education, Inc. All rights reserved.
61
17
18 // property that gets and sets
19 // base-salaried commission employee's base salary
20 public decimal BaseSalary
21 {
22 get
23 {
24 return baseSalary;
25 } // end get
26 set
27 {
28 baseSalary = ( value < 0 ) ? 0 : value;
29 } // end set
30 } // end property BaseSalary
Fig. 11.14 | BasePlusCommissionEmployee inherits from CommissionEmployeeand has access to CommissionEmployee's private data via its public
properties. (Part 2 of 3.)
Outline
BasePlusCommissionEmployee.cs
( 2 of 3 )
2009 Pearson Education, Inc. All rights reserved.
62
31
32 // calculate earnings
33 public override decimal Earnings()
34 {
35 return BaseSalary + base.Earnings();
36 } // end method Earnings
37
38 // return string representation of BasePlusCommissionEmployee
39 public override string ToString()
40 {
41 return string.Format( "base-salaried {0}\nbase salary: {1:C}",
42 base.ToString(), BaseSalary );
43 } // end method ToString
44 } // end class BasePlusCommissionEmployee
Fig. 11.14 | BasePlusCommissionEmployee inherits from CommissionEmployeeand has access to CommissionEmployee's private data via its public
properties. (Part 3 of 3.)
Outline
BasePlusCommissionEmployee.cs
( 3 of 3 )
Use CommissionEmployee’s Earnings method to calculate the commission pay, and add it to the BaseSalary.
2009 Pearson Education, Inc. All rights reserved.
63
11.4 Relationship between Base Classes and Derived Classes (Cont.)
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.
Common Programming Error 11.4
The use of “chained” base references to refer to amember several levels up the hierarchy—as in base.base.Earnings()—is a compilation error.
2009 Pearson Education, Inc. All rights reserved.
64
1 // Fig. 11.15: BasePlusCommissionEmployeeTest.cs
2 // Testing class BasePlusCommissionEmployee.
3 using System;
4
5 public class BasePlusCommissionEmployeeTest
6 {
7 public static void Main( string[] args )
8 {
9 // instantiate BasePlusCommissionEmployee4 object
10 BasePlusCommissionEmployee employee =
11 new BasePlusCommissionEmployee( "Bob", "Lewis",
12 "333-33-3333", 5000.00M, .04M, 300.00M );
13
14 // display base-salaried commission-employee data
15 Console.WriteLine(
16 "Employee information obtained by properties and methods: \n" );
• Figure 11.15 performs the same manipulations on a BasePlusCommissionEmployee object.
• By using inheritance and properties, we have efficiently and effectively constructed a well-engineered class.
Fig. 11.15 | Testing class BasePlusCommissionEmployee4. (Part 1 of 3.)
Outline
BasePlusCommissionEmployeeTest.cs
( 1 of 3 )
2009 Pearson Education, Inc. All rights reserved.
65
17 Console.WriteLine( "First name is {0}", employee.FirstName );
18 Console.WriteLine( "Last name is {0}", employee.LastName );
19 Console.WriteLine( "Social security number is {0}",
20 employee.SocialSecurityNumber );
21 Console.WriteLine( "Gross sales are {0:C}", employee.GrossSales );
22 Console.WriteLine( "Commission rate is {0:F2}",
23 employee.CommissionRate );
24 Console.WriteLine( "Earnings are {0:C}", employee.Earnings() );
25 Console.WriteLine( "Base salary is {0:C}", employee.BaseSalary );
26
27 employee.BaseSalary = 1000.00M; // set base salary
28
29 Console.WriteLine( "\n{0}:\n\n{1}",
30 "Updated employee information obtained by ToString", employee );
31 Console.WriteLine( "earnings: {0:C}", employee.Earnings() );
32 } // end Main
33 } // end class BasePlusCommissionEmployeeTest
Fig. 11.15 | Testing class BasePlusCommissionEmployee4. (Part 2 of 3.)
Outline
BasePlusCommissionEmployeeTest.cs
( 2 of 3 )
2009 Pearson Education, Inc. All rights reserved.
66
Employee information obtained by properties and methods:
First name is Bob
Last name is Lewis
Social security number is 333-33-3333
Gross sales are $5,000.00
Commission rate is 0.04
Earnings are $500.00
Base salary is $300.00
Updated employee information obtained by ToString:
base-salaried commission employee: Bob Lewis
social security number: 333-33-3333
gross sales: $5,000.00
commission rate: 0.04
base salary: $1,000.00
earnings: $1,200.00
Fig. 11.15 | Testing class BasePlusCommissionEmployee4. (Part 3 of 3.)
Outline
BasePlusCommissionEmployeeTest.cs
( 3 of 3 )
2009 Pearson Education, Inc. All rights reserved.
67
11.5 Constructors in Derived Classes
• The derived-class constructor, before performing its own tasks, invokes its direct base class’s constructor.
• This is done either explicitly or implicitly.
• If the base class is derived from another class, the base-class constructor invokes the constructor of the next class up in the hierarchy, and so on.
2009 Pearson Education, Inc. All rights reserved.
68
11.5 Constructors in Derived Classes (Cont.)
Software Engineering Observation 11.6When an application creates a derived-class object, the derived-class constructor calls the base-class constructor (explicitly, via 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 variableis still initialized to its default value.
2009 Pearson Education, Inc. All rights reserved.
69
1 // Fig. 11.16: CommissionEmployee.cs
2 // CommissionEmployee class represents a commission employee.
3 using System;
4
5 public class CommissionEmployee
6 {
7 private string firstName;
8 private string lastName;
9 private string socialSecurityNumber;
10 private decimal grossSales; // gross weekly sales
11 private decimal commissionRate; // commission percentage
12
13 // five-parameter constructor
14 public CommissionEmployee( string first, string last, string ssn,
15 decimal sales, decimal rate )
16 {
• Class CommissionEmployee (Fig. 11.16) is modifiedto output text when its constructor is invoked.
Fig. 11.16 | CommissionEmployee class represents a commission employee. (Part 1 of 5.)
Outline
CommissionEmployee.cs
( 1 of 5 )
2009 Pearson Education, Inc. All rights reserved.
70
17 // implicit call to object constructor occurs here
18 firstName = first;
19 lastName = last;
20 socialSecurityNumber = ssn;
21 GrossSales = sales; // validate gross sales via property
22 CommissionRate = rate; // validate commission rate via property
23
24 Console.WriteLine( "\nCommissionEmployee constructor:\n" + this );
25 } // end five-parameter CommissionEmployee constructor
26
27 // read-only property that gets commission employee's first name
28 public string FirstName
29 {
30 get
31 {
32 return firstName;
33 } // end get
34 } // end property FirstName
35
36 // read-only property that gets commission employee's last name
37 public string LastName
38 {
Fig. 11.16 | CommissionEmployee class represents a commission employee. (Part 2 of 5.)
Outline
CommissionEmployee.cs
( 2 of 5 )
2009 Pearson Education, Inc. All rights reserved.
71
39 get
40 {
41 return lastName;
42 } // end get
43 } // end property LastName
44
45 // read-only property that gets
46 // commission employee's social security number
47 public string SocialSecurityNumber
48 {
49 get
50 {
51 return socialSecurityNumber;
52 } // end get
53 } // end property SocialSecurityNumber
54
55 // property that gets and sets commission employee's gross sales
56 public decimal GrossSales
57 {
58 get
59 {
Fig. 11.16 | CommissionEmployee class represents a commission employee. (Part 3 of 5.)
Outline
CommissionEmployee.cs
( 3 of 5 )
2009 Pearson Education, Inc. All rights reserved.
72
60 return grossSales;
61 } // end get
62 set
63 {
64 grossSales = ( value < 0 ) ? 0 : value;
65 } // end set
66 } // end property GrossSales
67
68 // property that gets and sets commission employee's commission rate
69 public decimal CommissionRate
70 {
71 get
72 {
73 return commissionRate;
74 } // end get
75 set
76 {
77 commissionRate = ( value > 0 && value < 1 ) ? value : 0;
78 } // end set
79 } // end property CommissionRate
80
81 // calculate commission employee's pay
82 public virtual decimal Earnings()
83 {
Fig. 11.16 | CommissionEmployee class represents a commission employee. (Part 4 of 5.)
Outline
CommissionEmployee.cs
( 4 of 5 )
2009 Pearson Education, Inc. All rights reserved.
73
84 return CommissionRate * GrossSales;
85 } // end method Earnings
86
87 // return string representation of CommissionEmployee object
88 public override string ToString()
89 {
90 return string.Format(
91 "{0}: {1} {2}\n{3}: {4}\n{5}: {6:C}\n{7}: {8:F2}",
92 "commission employee", FirstName, LastName,
93 "social security number", SocialSecurityNumber,
94 "gross sales", GrossSales, "commission rate", CommissionRate );
95 } // end method ToString
96 } // end class CommissionEmployee
Fig. 11.16 | CommissionEmployee class represents a commission employee. (Part 5 of 5.)
Outline
CommissionEmployee.cs
( 5 of 5 )
2009 Pearson Education, Inc. All rights reserved.
74
1 // Fig. 11.17: BasePlusCommissionEmployee.cs
2 // BasePlusCommissionEmployee class declaration.
3 using System;
4
5 public class BasePlusCommissionEmployee : CommissionEmployee
6 {
7 private decimal baseSalary; // base salary per week
8
9 // six-parameter derived-class constructor
10 // with call to base class CommissionEmployee constructor
11 public BasePlusCommissionEmployee( string first, string last,
12 string ssn, decimal sales, decimal rate, decimal salary )
13 : base( first, last, ssn, sales, rate )
14 {
15 BaseSalary = salary; // validate base salary via property
• Class BasePlusCommissionEmployee (Fig. 11.17) is modified to output text when its constructor is invoked.
Fig. 11.17 | BasePlusCommissionEmployee class declaration. (Part 1 of 3.)
Outline
BasePlusCommissionEmployee.cs
( 1 of 3 )
2009 Pearson Education, Inc. All rights reserved.
75
16
17 Console.WriteLine(
18 "\nBasePlusCommissionEmployee5 constructor:\n" + this );
19 } // end six-parameter BasePlusCommissionEmployee constructor
20
21 // property that gets and sets
22 // base-salaried commission employee's base salary
23 public decimal BaseSalary
24 {
25 get
26 {
27 return baseSalary;
28 } // end get
29 set
30 {
31 baseSalary = ( value < 0 ) ? 0 : value;
32 } // end set
33 } // end property BaseSalary
34
Fig. 11.17 | BasePlusCommissionEmployee class declaration. (Part 2 of 3.)
Outline
BasePlusCommissionEmployee.cs
( 2 of 3 )
2009 Pearson Education, Inc. All rights reserved.
76
35 // calculate earnings
36 public override decimal Earnings()
37 {
38 return BaseSalary + base.Earnings();
39 } // end method Earnings
40
41 // return string representation of BasePlusCommissionEmployee
42 public override string ToString()
43 {
44 return string.Format( "base-salaried {0}\nbase salary: {1:C}",
45 base.ToString(), BaseSalary );
46 } // end method ToString
47 } // end class BasePlusCommissionEmployee
Fig. 11.17 | BasePlusCommissionEmployee class declaration. (Part 3 of 3.)
Outline
BasePlusCommissionEmployee.cs
( 3 of 3 )
2009 Pearson Education, Inc. All rights reserved.
77
1 // Fig. 10.18: ConstructorTest.cs
2 // Display order in which base-class and derived-class constructors
3 // are called.
4 using System;
5
6 public class ConstructorTest
7 {
8 public static void Main( string[] args )
9 {
10 CommissionEmployee employee1 = new CommissionEmployee( "Bob",
11 "Lewis", "333-33-3333", 5000.00M, .04M );
12
13 Console.WriteLine();
14 BasePlusCommissionEmployee employee2 =
15 new BasePlusCommissionEmployee( "Lisa", "Jones",
• Figure 11.18 demonstrates the order in which constructors are called in an inheritance hierarchy.
Fig. 11.18 | Display order in which base-class and derived-classconstructors are called. (Part 1 of 3.)
Outline
ConstructorTest.cs
( 1 of 3 )
2009 Pearson Education, Inc. All rights reserved.
78
16 "555-55-5555", 2000.00M, .06M, 800.00M );
17
18 Console.WriteLine();
19 BasePlusCommissionEmployee employee3 =
20 new BasePlusCommissionEmployee( "Mark", "Sands",
21 "888-88-8888", 8000.00M, .15M, 2000.00M );
22 } // end Main
23 } // end class ConstructorTest
CommissionEmployee constructor:
commission employee: Bob Lewis
social security number: 333-33-3333
gross sales: $5,000.00
commission rate: 0.04
CommissionEmployee constructor:
base-salaried commission employee: Lisa Jones
social security number: 555-55-5555
gross sales: $2,000.00
commission rate: 0.06
base salary: $0.00
(continued on next page...)
Fig. 11.18 | Display order in which base-class and derived-class
constructors are called. (Part 2 of 3.)
Outline
ConstructorTest.cs
( 2 of 3 )
2009 Pearson Education, Inc. All rights reserved.
79
(continued from previous page…)
BasePlusCommissionEmployee constructor:
base-salaried commission employee: Lisa Jones
social security number: 555-55-5555
gross sales: $2,000.00
commission rate: 0.06
base salary: $800.00
CommissionEmployee constructor:
base-salaried commission employee: Mark Sands
social security number: 888-88-8888
gross sales: $8,000.00
commission rate: 0.15
base salary: $0.00
BasePlusCommissionEmployee constructor:
base-salaried commission employee: Mark Sands
social security number: 888-88-8888
gross sales: $8,000.00
commission rate: 0.15
base salary: $2,000.00
Fig. 11.18 | Display order in which base-class and derived-classconstructors are called. (Part 3 of 3.)
Outline
ConstructorTest.cs
( 3 of 3 )
2009 Pearson Education, Inc. All rights reserved.
80
11.6 Software Engineering with Inheritance
• When a new class extends an existing class, the new class inherits the members of the existing class.
• We can customize the new class to meet our needs by including additional members and by overriding base-class members.
• 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.
2009 Pearson Education, Inc. All rights reserved.
81
11.6 Software Engineering with Inheritance (Cont.)
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.
• The availability of class libraries delivers the maxi mum benefits of software reuse.
2009 Pearson Education, Inc. All rights reserved.
82
11.6 Software Engineering with Inheritance (Cont.)
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.
Software Engineering Observation 11.9
Declaring a derived class does not affect its base class’s source code. Inheritance preserves the in tegrity of thebase class.
2009 Pearson Education, Inc. All rights reserved.
83
11.6 Software Engineering with Inheritance (Cont.)
Software Engineering Observation 11.10
Designers of object-oriented systems should avoid class proliferation. Such proliferation creates management problems and can hinder software reusability, because in a huge class library it becomes difficult for a client to locatethe most appropriate classes.
Performance Tip 11.1
If derived classes are larger than they need to be(i.e., contain too much functionality), memory and pro cessing resources might be wasted. Extend the base class containing the functionality that is closest to what is needed.
2009 Pearson Education, Inc. All rights reserved.
84
11.7 Class object
• All classes inherit directly or indirectly from the object class.
• Figure 11.19 summarizes object’s methods.
Method Description
Equals This method compares two objects for equality and returns true if they are equal and false otherwise.
Finalize Finalize is called by the garbage collector before it reclaims an object’s memory.
GetHashCode The hashcode value returned can be used by a hashtable to determine the location at which to insert the corresponding value.
Fig. 11.19 | object methods that are inherited directly or indirectlyby all classes. (Part 1 of 2.)
2009 Pearson Education, Inc. All rights reserved.
85
Method Description
GetType Returns an object of class Type that contains information about the object’s type.
MemberwiseClone This protected method makes a copy of the object on which it is called. Instance-variable values in one object are copied into another object of the same type. For reference types, only the references are copied.
ReferenceEquals This static method returns true if two objects are the same instance or if they are null references.
ToString Returns a string representation of an object. The default implementation returns the namespace and class name.
Fig. 11.19 | object methods that are inherited directly or indirectlyby all classes. (Part 2 of 2.)
11.7 Class object (Cont.)