1
11111111I t d tiIntroduction
to Visual Basicto Visual BasicProgramming:Programming:
Inheritance 2009 Pearson Education, Inc. All rights reserved.
Inheritance
2
S t k th ti lSay not you know another entirely, till you have divided an inheritance with him.
– Johann Kasper Lavater– Johann Kasper Lavater
This method is to define as the numberThis method is to define as the numberof a class the class of all classes similarto the given class.
– Bertrand Russell
2009 Pearson Education, Inc. All rights reserved.
3
G d it i t i h it libGood as it is to inherit a library,it is better to collect one.
– Augustine Birrell– Augustine Birrell
Save base authority from others’ books.Save base authority from others books.– William Shakespeare
2009 Pearson Education, Inc. All rights reserved.
4
OBJECTIVESOBJECTIVESIn this chapter you will learn:
Wh t i h it i d h it t What inheritance is and how it promotes software reusability.Th ti f b l d d i d The notions of base classes and derived classes.To use keyword I h it to create a class To use keyword Inherits to create a classthat inherits attributes and behaviors from another classanother class. To use the access modifier Protected in
a base class to give derived class
2009 Pearson Education, Inc. All rights reserved.
a base class to give derived classmethods access to base class members.
5
OBJECTIVESOBJECTIVES
T b l b f d i d To access base class members from a derived class with MyBase.H t t d i i h it How constructors are used in inheritance hierarchies.To access the current object with M and To access the current object with Me and MyClass. The methods of class Obj t the direct or The methods of class Object—the direct or
indirect base class of all classes in Visual Basic
2009 Pearson Education, Inc. All rights reserved.
Basic.
6
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 Object11.8 Friend Members
2009 Pearson Education, Inc. All rights reserved.
7
11 1 Introduction11.1 Introduction
I i h it l i t d b t di• In inheritance, a new class is created by extending an existing class’s members.
• The existing class is called the base class and the new• The existing class is called the base class, and the new class is the derived class.
• An indirect base class is inherited from two or more• An indirect base class is inherited from two or more levels up in the class hierarchy.
2009 Pearson Education, Inc. All rights reserved.
8
11 1 Introduction (Cont )11.1 Introduction (Cont.)
E l i Vi l B i t d ( “i h it• Every class in Visual Basic extends (or “inherits from”) Object.
• An is a relationship represents inheritance For• An is-a relationship represents inheritance. For example, a car is a vehicle.
• By contrast the has-a relationship represents• By contrast, the has-a relationship represents composition. For example, a car has a steering wheel.
2009 Pearson Education, Inc. All rights reserved.
9
11.2 Base Classes and Derived Classes
• Figure 11.1 lists several simple examples of base classes and derived classesclasses and derived classes.
Base class Derived classes
Student GraduateStudent, UndergraduateStudent
Shape Circle Triangle Rectangle Shape Circle, Triangle, Rectangle
Loan CarLoan, HomeImprovementLoan, MortgageLoan
Employee Faculty, Staff
BankAccount CheckingAccount, SavingsAccount
Fig. 11.1 | Inheritance examples.
g g
2009 Pearson Education, Inc. All rights reserved.
10
11.2 Base Classes and Derived Classes (Cont.)
A i h it hi h h th l ti hi• An inheritance hierarchy shows the relationship between classes.
Fig. 11.2 | Inheritance hierarchy for university CommunityMembers.
2009 Pearson Education, Inc. All rights reserved.
11
11.2 Base Classes and Derived Classes (Cont.)
Fig. 11.3 | Inheritance hierarchy for Shapes.
2009 Pearson Education, Inc. All rights reserved.
12
11 3 Protected Members11.3 Protected Members
Protected members can be accessed onl b the• Protected members can be accessed only by the class and its derived classes.
• Public and Protected members retain their• Public and Protected members retain their original access modifiers in derived classes.
• When a derived class method overrides a method the• When a derived class method overrides a method, the base class version can be accessed from the derived class with keyword MyBase.y y
2009 Pearson Education, Inc. All rights reserved.
13
11 3 Protected Members (Cont )11.3 Protected Members (Cont.)
Software Engineering Observation 11.1Derived class methods cannot directly access Private members of their base class. A derived class can change the state of Privatebase class instance variables only through non-Private methods y gprovided in the base class and inherited by the derived class.
Software Engineering Observation 11.2g gDeclaring Private instance variables helps programmers test, debug and correctly modify systems. If a derived class could access its base class’s Private instance variables classes that inheritits base class s Private instance variables, classes that inherit from that derived class could access the instance variables as well. This would propagate access to what should be Private instance variables and the benefits of information hiding would be lost
2009 Pearson Education, Inc. All rights reserved.
variables, and the benefits of information hiding would be lost.
14Outline• CommissionEmployees are paid a percentage of
their sales (Fig. 11.4). 1 ' Fig. 11.4: CommmissionEmployee.vb
2 ' CommissionEmployee class represents a commission employee.
3 Public Class CommissionEmployee
4 Inherits Object ' optional
CommmissionEmployee.vb
( 1 of 6 ) 5 6 Private firstNameValue As String ' first name
7 Private lastNameValue As String ' last name
8 Private socialSecurityNumberValue As String ' social security number
9 Private grossSalesValue As Decimal ' gross weekly sales
( 1 of 6 )
CommissionEmployeeInherits from class Object.
9 Private grossSalesValue As Decimal gross weekly sales
10 Private commissionRateValue As Double ' commission percentage 11 12 ' five-argument constructor 13 Public Sub New(ByVal first As String, ByVal last As String, _
Each instance variable is Private.
14 ByVal ssn As String, ByVal sales As Decimal, ByVal rate As Double) 15 16 ' implicit call to Object constructor occurs here 17 FirstName = first 18 LastName = last
A constructor’s first task is to call the base class’s constructor implicitly.
19 SocialSecurityNumber = ssn 20 GrossSales = sales ' validate and store gross sales 21 CommissionRate = rate ' validate and store commission rate 22 End Sub ' New
Setting instance variables through properties.
2009 Pearson Education, Inc. All rights reserved.
Fig. 11.4 | CommissionEmployee class represents an employeepaid a percentage of gross sales. (Part 1 of 5.)
15Outline
23 24 ' property FirstName 25 Public Property FirstName() As String 26 Get 27 Return firstNameValue
CommmissionEmployee.vb
( 2 of 6 )27 Return firstNameValue 28 End Get 29 30 Set(ByVal first As String) 31 firstNameValue = first ' no validation
( 2 of 6 )
32 End Set 33 End Property ' FirstName 34 35 ' property LastName 36 Public Property LastName() As String p y () g
37 Get 38 Return lastNameValue 39 End Get 40 41 Set(ByVal last As String) 41 Set(ByVal last As String) 42 lastNameValue = last ' no validation 43 End Set 44 End Property ' LastName
2009 Pearson Education, Inc. All rights reserved.
Fig. 11.4 | CommissionEmployee class represents an employeepaid a percentage of gross sales. (Part 2 of 5.)
16Outline
45 46 ' property SocialSecurityNumber 47 Public Property SocialSecurityNumber() As String
CommmissionEmployee.vb
( 3 of 6 )p y y () g
48 Get 49 Return socialSecurityNumberValue 50 End Get 51 52 Set(ByVal ssn As String)
( 3 of 6 )
52 Set(ByVal ssn As String) 53 socialSecurityNumberValue = ssn ' no validation 54 End Set 55 End Property ' SocialSecurityNumber 56 57 ' property GrossSales 58 Public Property GrossSales() As Decimal 59 Get 60 Return grossSalesValue 61 End Get 62
Fig. 11.4 | CommissionEmployee class represents an employeepaid a percentage of gross sales. (Part 3 of 5.)
2009 Pearson Education, Inc. All rights reserved.
17Outline
63 Set(ByVal sales As Decimal) 64 If sales < 0D Then ' validate gross sales 65 grossSalesValue = 0D 66 Else 67 grossSalesValue = sales
CommmissionEmployee.vb
( 4 of 6 )67 grossSalesValue = sales 68 End If 69 End Set 70 End Property ' GrossSales 71
Validating GrossSales.
( 4 of 6 )
72 ' property CommissionRate 73 Public Property CommissionRate() As Double 74 Get 75 Return commissionRateValue 76 End Get 77 78 Set(ByVal rate As Double) 79 If rate > 0.0 AndAlso rate < 1.0 Then ' validate rate 80 commissionRateValue = rate 81 Else
Validating CommissionRate.
81 Else 82 commissionRateValue = 0.0 83 End If 84 End Set
2009 Pearson Education, Inc. All rights reserved.
Fig. 11.4 | CommissionEmployee class represents an employeepaid a percentage of gross sales. (Part 4 of 5.)
18Outline
85 End Property ' CommissionRate 86
CommmissionEmployee.vb
( 5 of 6 )87 ' calculate earnings 88 Public Function CalculateEarnings() As Decimal 89 Return Convert.ToDecimal(commissionRateValue) * grossSalesValue 90 End Function ' CalculateEarnings 91
CalculateEarnings calculates a CommissionEmployee’s earnings.
( 5 of 6 )
91 92 ' return String representation of CommissionEmployee object 93 Public Overrides Function ToString() As String 94 Return ("commission employee: " & firstNameValue & " " & _ 95 lastNameValue & vbNewLine & "social security number: " & _
ToString Overrides class96 socialSecurityNumberValue & vbNewLine & "gross sales: " & _ 97 String.Format("{0:C}", grossSalesValue) & vbNewLine & _ 98 "commission rate: " & String.Format("{0:F}", _ 99 commissionRateValue)) 100 End Function ' ToString
ToString Overrides class Object’s ToString method.
00 d u ct o oSt g
101 End Class ' CommissionEmployee
Fig. 11.4 | CommissionEmployee class represents an employeepaid a percentage of gross sales (Part 5 of 5 )
2009 Pearson Education, Inc. All rights reserved.
paid a percentage of gross sales. (Part 5 of 5.)
19Outline
Common Programming Error 11.1It is a compilation error to attempt to override a
CommmissionEmployee.vb
( 6 of 6 )It is a compilation error to attempt to override a method that is not declared Overridable.
( 6 of 6 )
Common Programming Error 11.2It is a compilation error to override a methodIt is a compilation error to override a method with a method that has a different access modifier than the method being overridden.
2009 Pearson Education, Inc. All rights reserved.
20Outline
1 ' Fig. 11.5: CommissionEmployeeTest.vb
2 ' Testing class CommissionEmployee.
CommissionEmployeeTest.vb
( 1 of 2 )g p y
3 Module CommissionEmployeeTest
4 Sub Main()
5 ' instantiate CommissionEmployee object
6 Dim employee As New CommissionEmployee( _
7 "Sue" "Jones" "222 22 2222" 10000D 0 06)
( 1 of 2 )
Initializing a CommissionEmployeebj 7 Sue , Jones , 222-22-2222 , 10000D, 0.06)
8 9 ' get commission employee data
10 Console.WriteLine("Employee information obtained by properties:" _ 11 & vbNewLine & "First name is " & employee.FirstName & _
object.
12 vbNewLine & "Last name is " & employee.LastName & vbNewLine & _ 13 "Social Security Number is " & employee.SocialSecurityNumber) 14 Console.WriteLine("Gross sales is {0:C}", employee.GrossSales) 15 Console.WriteLine("Commission rate is {0:F}", _ 16 employee.CommissionRate)
Accessing employee’sproperties.
p y )
Fig. 11.5 | CommissionEmployee class testprogram. (Part 1 of 2.)
2009 Pearson Education, Inc. All rights reserved.
21
17 18 employee.GrossSales = 500D ' set gross sales 19 employee.CommissionRate = 0.1 ' set commission rate to 10%
Outline
20 21 ' get new employee information 22 Console.WriteLine(vbNewLine & _ 23 "Updated employee information obtained by ToString: " & _ 24 vbNewLine & employee.ToString() & vbNewLine)
CommissionEmployeeTest.vb
( 2 of 2 )25 26 ' display the employee's earnings 27 Console.WriteLine("Employee's earnings: {0:C}", _ 28 employee.CalculateEarnings()) 29 End Sub ' Main
Setting employee’s properties.
( 2 of 2 )
29 End Sub Main
30 End Module ' CommissionEmployeeTest
Employee information obtained by properties:
First name is Sue
Last name is Jones
Explicitly calling CommissionEmployee’s ToString method.
Di l i iSocial Security Number is 222-22-2222
Gross sales is $10,000.00
Commission rate is 0.06
Updated employee information obtained by ToString:
i i l
Displaying earnings calculated by the object’s CalculateEarningsmethod.
commission employee: Sue Jones
social security number: 222-22-2222
gross sales: $500.00
commission rate: 0.10
Employee's earnings: $50 00
2009 Pearson Education, Inc. All rights reserved.
Employee s earnings: $50.00
Fig. 11.5 | CommissionEmployee class test
program. (Part 2 of 2.)
22Outline• BasePlusCommissionEmployee is a separate
class with a similar function (Fig. 11.6).
1 ' Fig. 11.6: BasePlusCommissionEmployee.vb
2 ' BasePlusCommissionEmployee class represents an employee that receives
3 ' a base salary in addition to a commission.
4 P bli Cl B Pl C i i E l
BasePlusCommissionEmployee.vb
( 1 of 7 ) 4 Public Class BasePlusCommissionEmployee
5 Private firstNameValue As String ' first name
6 Private lastNameValue As String ' last name
7 Private socialSecurityNumberValue As String ' social security number
8 Private grossSalesValue As Decimal ' gross weekly sales
( 1 of 7 )
9 Private commissionRateValue As Double ' commission percentage
10 Private baseSalaryValue As Decimal ' base salary per week 11 12 ' six-argument constructor 13 Public Sub New(ByVal first As String, ByVal last As String,
A BasePlusCommissionEmployee has an additional baseSalaryValue variable.
13 Public Sub New(ByVal first As String, ByVal last As String, _ 14 ByVal ssn As String, ByVal sales As Decimal, _ 15 ByVal rate As Double, ByVal salary As Decimal) 16
The BasePlusCommissionEmployeeconstructor has an additional salaryparameter.
Fig. 11.6 | BasePlusCommissionEmployee class represents an employee who receives a base salary in addition to a commission. (Part 1 of 7.)
2009 Pearson Education, Inc. All rights reserved.
23Outline
17 ' implicit call to Object constructor occurs here 18 FirstName = first 19 LastName = last 20 SocialSecurityNumber = ssn
BasePlusCommissionEmployee.vb
( 2 of 7 )20 SocialSecurityNumber = ssn 21 GrossSales = sales ' validate and store gross sales 22 CommissionRate = rate ' validate and store commission rate 23 BaseSalary = salary ' validate and store base salary 24 End Sub ' New 25
A BasePlusCommissionEmployeehas an additional BaseSalaryproperty.
( 2 of 7 )
25 26 ' property FirstName 27 Public Property FirstName() As String 28 Get 29 Return firstNameValue 30 End Get 31 32 Set(ByVal first As String) 33 firstNameValue = first ' no validation 34 End Set 34 End Set 35 End Property ' FirstName 36
Fig. 11.6 | BasePlusCommissionEmployee class represents an employee who
2009 Pearson Education, Inc. All rights reserved.
g | p y p p yreceives a base salary in addition to a commission. (Part 2 of 7.)
24Outline
37 ' property LastName 38 Public Property LastName() As String 39 Get 40 Return lastNameValue
BasePlusCommissionEmployee.vb
( 3 of 7 )40 Return lastNameValue 41 End Get 42 43 Set(ByVal last As String) 44 lastNameValue = last ' no validation
( 3 of 7 )
45 End Set 46 End Property ' LastName 47 48 ' property SocialSecurityNumber 49 Public Property SocialSecurityNumber() As String p y y () g
50 Get 51 Return socialSecurityNumberValue 52 End Get 53 54 Set(ByVal ssn As String) 54 Set(ByVal ssn As String) 55 socialSecurityNumberValue = ssn ' no validation 56 End Set 57 End Property ' SocialSecurityNumber
2009 Pearson Education, Inc. All rights reserved.
Fig. 11.6 | BasePlusCommissionEmployee class represents an employee who receives a base salary in addition to a commission. (Part 3 of 7.)
25Outline
58 59 ' property GrossSales 60 Public Property GrossSales() As Decimal 61 Get
BasePlusCommissionEmployee.vb
( 4 of 7 )61 Get 62 Return grossSalesValue 63 End Get 64 65 Set(ByVal sales As Decimal)
( 4 of 7 )
66 If sales < 0D Then ' validate gross sales 67 grossSalesValue = 0D 68 Else 69 grossSalesValue = sales 70 End If 71 End Set 72 End Property ' GrossSales 73 74 ' property CommissionRate 75 Public Property CommissionRate() As Double 75 Public Property CommissionRate() As Double 76 Get 77 Return commissionRateValue 78 End Get
2009 Pearson Education, Inc. All rights reserved.
Fig. 11.6 | BasePlusCommissionEmployee class represents an employee who receives a base salary in addition to a commission. (Part 4 of 7.)
26Outline
79 80 Set(ByVal rate As Double)
BasePlusCommissionEmployee.vb
( 5 of 7 )( y )
81 If rate > 0.0 AndAlso rate < 1.0 Then ' validate rate 82 commissionRateValue = rate 83 Else 84 commissionRateValue = 0.0 85 End If
( 5 of 7 )
85 End If 86 End Set 87 End Property ' CommissionRate 88 89 ' property BaseSalary 90 Public Property BaseSalary() As Decimal 91 Get 92 Return baseSalaryValue 93 End Get 94
The additional BaseSalaryproperty validates its input.
Fig. 11.6 | BasePlusCommissionEmployee class represents an employee who receives a base salary in addition to a commission. (Part 5 of 7.)
2009 Pearson Education, Inc. All rights reserved.
27Outline
95 Set(ByVal salary As Decimal) 96 If salary < 0D Then ' validate base salary
BasePlusCommissionEmployee.vb
( 6 of 7 )y y
97 baseSalaryValue = 0D 98 Else 99 baseSalaryValue = salary 100 End If 101 End Set
The additional BaseSalaryproperty validates its input.
( 6 of 7 )
101 End Set 102 End Property ' BaseSalary 103 104 ' calculate earnings 105 Public Function CalculateEarnings() As Decimal CalculateEarnings
106 Return baseSalaryValue + ( _ 107 Convert.ToDecimal(commissionRateValue) * grossSalesValue) 108 End Function ' CalculateEarnings 109
calculates a BasePlusCommissionEmployee’s earnings.
Fig. 11.6 | BasePlusCommissionEmployee class represents an employee who receives a base salary in addition to a commission. (Part 6 of 7.)
2009 Pearson Education, Inc. All rights reserved.
28Outline
110 ' return String representation of BasePlusCommissionEmployee object 111 Public Overrides Function ToString() As String
BasePlusCommissionEmployee.vb
( 7 of 7 )g g
112 Return ("base-plus-commission employee: " & firstNameValue & " " & _ 113 lastNameValue & vbNewLine & "social security number: " & _ 114 socialSecurityNumberValue & vbNewLine & "gross sales: " & _ 115 String.Format("{0:C}", grossSalesValue) & vbNewLine & _ 116 "commission rate: " & String.Format("{0:F}",
( 7 of 7 )
116 commission rate: & String.Format( {0:F} , _
117 commissionRateValue) & vbNewLine & "base salary: " & _ 118 String.Format("{0:C}", baseSalaryValue)) 119 End Function ' ToString 120 End Class ' BasePlusCommissionEmployee
Changing LinkColor to show a visited item.
Fig. 11.6 | BasePlusCommissionEmployee class represents an employee who receives a base salary in addition to a commission. (Part 7 of 7.)
2009 Pearson Education, Inc. All rights reserved.
29Outline• Figure 11.7 tests class
BasePlusCommissionEmployee.
BasePlusCommissionEmployeeTest.vb
( 1 of 2 )
• The BasePlusCommissionEmployee constructor is almost identical to that of class CommissionEmployee
1 ' Fig. 11.7: BasePlusCommissionEmployeeTest.vb
2 ' Testing class BasePlusCommissionEmployee.
3 Module BasePlusCommissionEmployeeTest
( 1 of 2 )CommissionEmployee.
4 Sub Main()
5 ' instantite BasePlusCommissionEmployee object
6 Dim employee As New BasePlusCommissionEmployee( _
7 "Bob", "Lewis", "333-33-3333", 5000D, 0.04, 300D)
8
Initializing aBasePlusCommissionEmployee object.
9 ' get base-salaried commission employee data
10 Console.WriteLine("Employee information obtained by properties:" _ 11 & vbNewLine & "First name is " & employee.FirstName & _ 12 vbNewLine & "Last name is " & employee.LastName & vbNewLine & _ 13 "Social Security Number is " & employee.SocialSecurityNumber)
Accessing employee’s i13 Social Security Number is & employee.SocialSecurityNumber)
14 Console.WriteLine("Gross sales is {0:C}", employee.GrossSales) 15 Console.WriteLine("Commission rate is {0:F}", _
properties.
Fig. 11.7 | BasePlusCommissionEmployee test program. (Part 1 of 2.)
2009 Pearson Education, Inc. All rights reserved.
3016 employee.CommissionRate) 17 Console.WriteLine("Base salary is {0:C}", employee.BaseSalary) 18 19 employee.BaseSalary = 1000D ' set base salary
Outline
20 21 ' get new employee information 22 Console.WriteLine(vbNewLine & _ 23 "Updated employee information obtained by ToString: " & _ 24 vbNewLine & employee.ToString() & vbNewLine)
BasePlusCommissionEmployeeTest.vb
( 2 of 2 )25 26 ' display the employee's earnings 27 Console.WriteLine("Employee's earnings: {0:C}" & _ 28 employee.CalculateEarnings()) 29 End Sub ' Main
Accessing employee’s properties.
( 2 of 2 )
30 End Module ' BasePlusCommissionEmployeeTest
Employee information obtained by properties:
First name is Bob
Last name is Lewis
Social Security Number is 333-33-3333
Setting the BaseSalaryproperty.
Invoking the object’sSocial Security Number is 333 33 3333
Gross sales is $5,000.00
Commission rate is 0.04
Base salary is $300.00
Updated employee information obtained by ToString:
base plus commission employee: Bob Lewis
Invoking the object s ToString method explicitly.
Displaying earnings base-plus-commission employee: Bob Lewis
social security number: 333-33-3333
gross sales: $5,000.00
commission rate: 0.04
base salary: $1,000.00
sp ay g ea gscalculated by the object’s CalculateEarningsmethod.
2009 Pearson Education, Inc. All rights reserved.
Employee's earnings: $1,200.00
Fig. 11.7 | BasePlusCommissionEmployee test
program. (Part 2 of 2.)
31
Software Engineering Observation 11.3Copying and pasting code from one class to another
d l i l d filcan spread errors among multiple source code files.
Software Engineering Observation 11 4Software Engineering Observation 11.4With inheritance, the common instance variables and methods of all the classes in the hierarchy are declared in a base class. When changes are required for these common features, software developers need to make the changes only in the base class—derived classes then inherit the changes. Without inheritance, the changes would need to be made to all the source code files that contain copies of the code in question.
2009 Pearson Education, Inc. All rights reserved.
p q
32Outline
• Method CalculateEarnings is now declared Overridable (Fig 11 8)
1 ' Fig. 11.8: CommmissionEmployee.vb
2 ' CommissionEmployee class represents a commission employee.
3 Public Class CommissionEmployee
4 I h it Obj t ' ti l
CommmissionEmployee.vb
( 1 of 6 )
Overridable (Fig. 11.8).
4 Inherits Object ' optional
5 6 Private firstNameValue As String ' first name
7 Private lastNameValue As String ' last name
8 Private socialSecurityNumberValue As String ' social security number
( 1 of 6 )
9 Private grossSalesValue As Decimal ' gross weekly sales
10 Private commissionRateValue As Double ' commission percentage 11 12 ' five-argument constructor 13 Public Sub New(ByVal first As String, ByVal last As String, 13 Public Sub New(ByVal first As String, ByVal last As String, _ 14 ByVal ssn As String, ByVal sales As Decimal, ByVal rate As Double) 15 16 ' implicit call to Object constructor occurs here 17 FirstName = first 18 L tN l t 18 LastName = last 19 SocialSecurityNumber = ssn 20 GrossSales = sales ' validate and store gross sales 21 CommissionRate = rate ' validate and store commission rate 22 End Sub ' New
2009 Pearson Education, Inc. All rights reserved.
Fig. 11.8 | CommissionEmployee class with Overridablemethod CalculateEarnings. (Part 1 of 6.)
33Outline
23 24 ' property FirstName 25 Public Property FirstName() As String 26 Get
CommmissionEmployee.vb
( 2 of 6 )26 Get 27 Return firstNameValue 28 End Get 29 30 Set(ByVal first As String) 31 fi tN V l fi t ' lid ti
( 2 of 6 )
31 firstNameValue = first ' no validation 32 End Set 33 End Property ' FirstName 34 35 ' property LastName 36 Public Property LastName() As String 37 Get 38 Return lastNameValue 39 End Get 4040 41 Set(ByVal last As String) 42 lastNameValue = last ' no validation 43 End Set 44 End Property ' LastName
2009 Pearson Education, Inc. All rights reserved.
Fig. 11.8 | CommissionEmployee class with Overridablemethod CalculateEarnings. (Part 2 of 6.)
34Outline
45 46 ' property SocialSecurityNumber
CommmissionEmployee.vb
( 3 of 6 )p p y y
47 Public Property SocialSecurityNumber() As String 48 Get 49 Return socialSecurityNumberValue 50 End Get 51
( 3 of 6 )
51 52 Set(ByVal ssn As String) 53 socialSecurityNumberValue = ssn ' no validation 54 End Set 55 End Property ' SocialSecurityNumber 56 57 ' property GrossSales 58 Public Property GrossSales() As Decimal 59 Get 60 Return grossSalesValue g
61 End Get 62
Fig. 11.8 | CommissionEmployee class with Overridable
2009 Pearson Education, Inc. All rights reserved.
gmethod CalculateEarnings. (Part 3 of 6.)
35Outline
63 Set(ByVal sales As Decimal) 64 If sales < 0D Then ' validate gross sales
CommmissionEmployee.vb
( 4 of 6 )g
65 grossSalesValue = 0D 66 Else 67 grossSalesValue = sales 68 End If 69 End Set
( 4 of 6 )
70 End Property ' GrossSales 71 72 ' property CommissionRate 73 Public Property CommissionRate() As Decimal 74 Get 74 Get 75 Return commissionRateValue 76 End Get
Fig. 11.8 | CommissionEmployee class with Overridablemethod CalculateEarnings. (Part 4 of 6.)
2009 Pearson Education, Inc. All rights reserved.
36Outline
77 8 ( l i l)
CommmissionEmployee.vb
( 5 of 6 )78 Set(ByVal rate As Decimal) 79 If rate > 0.0 AndAlso rate < 1.0 Then ' validate rate 80 commissionRateValue = rate 81 Else 82 commissionRateValue = 0.0
( 5 of 6 )
83 End If 84 End Set 85 End Property ' CommissionRate 86 87 ' calculate earnings CalculateEarnings
l l88 Public Overridable Function CalculateEarnings() As Decimal 89 Return Convert.ToDecimal(commissionRateValue) * grossSalesValue 90 End Function ' CalculateEarnings
calculates a CommissionEmployee’s earnings.
Fi 11 8 | C i i E l l ith O id blFig. 11.8 | CommissionEmployee class with Overridablemethod CalculateEarnings. (Part 5 of 6.)
2009 Pearson Education, Inc. All rights reserved.
37Outline
91 92 ' return String representation of CommissionEmployee object
CommmissionEmployee.vb
( 6 of 6 )g p p y j
93 Public Overrides Function ToString() As String 94 Return ("commission employee: " & firstNameValue & " " & _ 95 lastNameValue & vbNewLine & "social security number: " & _ 96 socialSecurityNumberValue & vbNewLine & "gross sales: " & _ 97 String Format("{0:C}" grossSalesValue) & vbNewLine &
( 6 of 6 )
97 String.Format( {0:C} , grossSalesValue) & vbNewLine & _
98 "commission rate: " & String.Format("{0:F}", _ 99 commissionRateValue)) 100 End Function ' ToString 101 End Class ' CommissionEmployee
Fig. 11.8 | CommissionEmployee class with Overridablemethod CalculateEarnings. (Part 6 of 6.)
2009 Pearson Education, Inc. All rights reserved.
38Outline
• BasePlusCommissionEmployee (Fig. 11.9) now inherits from CommissionEmployee
1 ' Fig. 11.9: BasePlusCommissionEmployee.vb
2 ' BasePlusCommissionEmployee inherits from class CommissionEmployee.
BasePlusCommissionEmployee.vb
( 1 of 3 )
inherits from CommissionEmployee.
p y p y
3 Public Class BasePlusCommissionEmployee
4 Inherits CommissionEmployee
5 6 Private baseSalaryValue As Decimal ' base salary per week
7
( 1 of 3 )
Class BasePlusCommisssionEmployee inherits from class CommissionEmployee. 7
8 ' six-argument constructor
9 Public Sub New(ByVal first As String, ByVal last As String, _
10 ByVal ssn As String, ByVal sales As Decimal, _ 11 ByVal rate As Double, ByVal salary As Decimal) 1212 13 ' use MyBase to invoke CommissionEmployee constructor explicitly 14 MyBase.New(first, last, ssn, sales, rate) 15 BaseSalary = salary ' validate and store base salary 16 End Sub ' New 17
Explicitly calling the base class constructor with MyBase.
17 18 ' property BaseSalary 19 Public Property BaseSalary() As Decimal 20 Get 21 Return baseSalaryValue
d
2009 Pearson Education, Inc. All rights reserved.
22 End Get
Fig. 11.9 | Private base class members cannot be accessedin a derived class. (Part 1 of 3.)
39Outline
23 24 Set(ByVal salary As Decimal)
BasePlusCommissionEmployee.vb
( 2 of 3 )( y y )
25 If salary < 0D Then ' validate base salary 26 baseSalaryValue = 0D 27 Else 28 baseSalaryValue = salary 29 End If
( 2 of 3 )
29 End If 30 End Set 31 End Property ' BaseSalary 32 33 ' calculate earnings 34 Public Overrides Function CalculateEarnings() As Decimal 34 Public Overrides Function CalculateEarnings() As Decimal 35 ' not allowed: attempts to access private base class members 36 Return baseSalaryValue + ( _ 37 Convert.ToDecimal(commissionRateValue) * grossSalesValue) 38 End Function ' CalculateEearnings 3939
Fig. 11.9 | Private base class members cannot be accessedin a derived class. (Part 2 of 3.)
2009 Pearson Education, Inc. All rights reserved.
40
40 ' return String representation of BasePlusCommissionEmployee object 41 Public Overrides Function ToString() As String
Outline
42 ' not allowed: attempts to access private base class members 43 Return ("base-plus-commission employee: " & firstNameValue & _ 44 " " & lastNameValue & vbNewLine & "social security number: " & _ 45 socialSecurityNumberValue & vbNewLine & "gross sales: " & _ 46 String.Format("{0:C}", grossSalesValue) & vbNewLine & _
BasePlusCommissionEmployee.vb
( 3 of 3 )47 "commission rate: " & String.Format("{0:F}", _ 48 commissionRateValue) & vbNewLine & "base salary: " & _ 49 String.Format("{0:C}", baseSalaryValue)) 50 End Function ' ToString 51 End Class ' BasePlusCommissionEmployee
Private instance variables are not inherited.
( 3 of 3 )
2009 Pearson Education, Inc. All rights reserved.
Fig. 11.9 | Private base class members cannot be accessedin a derived class. (Part 3 of 3.)
41Outline
• Class CommissionEmployee (Fig. 11.10) declares its instance variables as Protected rather than
CommmissionEmployee.vb
( 1 of 6 )
its instance variables as Protected rather than Private.
• Derived classes gain access to these instance variables. 1 ' Fig. 11.10: CommmissionEmployee.vb
2 ' CommissionEmployee class represents a commission employee.
3 Public Class CommissionEmployee
4 Inherits Object ' optional
( 1 of 6 )Derived classes gain access to these instance variables.
5 6 Protected firstNameValue As String ' first name
7 Protected lastNameValue As String ' last name
8 Protected socialSecurityNumberValue As String ' social security number
9 Protected grossSalesValue As Decimal ' gross weekly sales
Protectedinstance variables are inherited by derived classes
10 Protected commissionRateValue As Double ' commission percentage 11 12 ' five-argument constructor 13 Public Sub New(ByVal first As String, ByVal last As String, _ 14 ByVal ssn As String, ByVal sales As Decimal, ByVal rate As Double)
derived classes.
y g, y , y )
15 16 ' implicit call to Object constructor occurs here 17 FirstName = first
Fi 11 10 i i l l ith d
2009 Pearson Education, Inc. All rights reserved.
Fig. 11.10 | CommissionEmployee class with Protectedinstance variables. (Part 1 of 6.)
4218 LastName = last 19 SocialSecurityNumber = ssn 20 GrossSales = sales ' validate and store gross sales 21 CommissionRate = rate ' validate and store commission rate
Outline
21 CommissionRate rate validate and store commission rate
22 End Sub ' New 23 24 ' property FirstName 25 Public Property FirstName() As String 26 Get
CommmissionEmployee.vb
( 2 of 6 )26 Get 27 Return firstNameValue 28 End Get 29 30 Set(ByVal first As String)
( 2 of 6 )
31 firstNameValue = first ' no validation 32 End Set 33 End Property ' FirstName 34 35 ' property LastName 36 Public Property LastName() As String 37 Get 38 Return lastNameValue 39 End Get 4040 41 Set(ByVal last As String) 42 lastNameValue = last ' no validation 43 End Set 44 End Property ' LastName
2009 Pearson Education, Inc. All rights reserved.
Fig. 11.10 | CommissionEmployee class with Protectedinstance variables. (Part 2 of 6.)
43Outline
45 46 ' property SocialSecurityNumber
CommmissionEmployee.vb
( 3 of 6 )p p y y
47 Public Property SocialSecurityNumber() As String 48 Get 49 Return socialSecurityNumberValue 50 End Get 51
( 3 of 6 )
51 52 Set(ByVal ssn As String) 53 socialSecurityNumberValue = ssn ' no validation 54 End Set 55 End Property ' SocialSecurityNumber 56 57 ' property GrossSales 58 Public Property GrossSales() As Decimal 59 Get 60 Return grossSalesValue g
61 End Get 62
Fig. 11.10 | CommissionEmployee class with Protected
2009 Pearson Education, Inc. All rights reserved.
instance variables. (Part 3 of 6.)
44Outline
63 Set(ByVal sales As Decimal) 64 If sales < 0D Then ' validate gross sales
CommmissionEmployee.vb
( 4 of 6 )g
65 grossSalesValue = 0D 66 Else 67 grossSalesValue = sales 68 End If 69 End Set
( 4 of 6 )
69 End Set 70 End Property ' GrossSales 71 72 ' property CommissionRate 73 Public Property CommissionRate() As Double 74 Get 75 Return commissionRateValue 76 End Get
Fig 11 10 | CommissionEmployee class ith ProtectedFig. 11.10 | CommissionEmployee class with Protectedinstance variables. (Part 4 of 6.)
2009 Pearson Education, Inc. All rights reserved.
45Outline
77 78 Set(ByVal rate As Double)
CommmissionEmployee.vb
( 5 of 6 )( y )
79 If rate > 0.0 AndAlso rate < 1.0 Then ' validate rate 80 commissionRateValue = rate 81 Else 82 commissionRateValue = 0.0 83 End If
( 5 of 6 )
83 End If 84 End Set 85 End Property ' CommissionRate 86 87 ' calculate earnings 88 Public Overridable Function CalculateEarnings() As Decimal 89 Return Convert.ToDecimal(commissionRateValue) * grossSalesValue 90 End Function ' CalculateEarnings
Fig 11 10 | CommissionEmployee class with ProtectedFig. 11.10 | CommissionEmployee class with Protectedinstance variables. (Part 5 of 6.)
2009 Pearson Education, Inc. All rights reserved.
46Outline
91 92 ' return String representation of CommissionEmployee object
CommmissionEmployee.vb
( 6 of 6 )93 Public Overrides Function ToString() As String 94 Return ("commission employee: " & firstNameValue & " " & _ 95 lastNameValue & vbNewLine & "social security number: " & _ 96 socialSecurityNumberValue & vbNewLine & "gross sales: " & _ 97 String Format("{0:C}" grossSalesValue) & vbNewLine &
( 6 of 6 )
97 String.Format( {0:C} , grossSalesValue) & vbNewLine & _
98 "commission rate: " & String.Format("{0:F}", _ 99 commissionRateValue)) 100 End Function ' ToString 101 End Class ' CommissionEmployee
Fig. 11.10 | CommissionEmployee class with Protected
instance variables. (Part 6 of 6.)
2009 Pearson Education, Inc. All rights reserved.
47Outline
• Modify BasePlusCommissionEmployeeBasePlusCommissionEmployee.vb
( 1 of 3 )
Modify BasePlusCommissionEmployee(Fig. 11.9) so that it inherits from CommissionEmployee.
1 ' Fig. 11.11: BasePlusCommissionEmployee.vb
2 ' BasePlusCommissionEmployee inherits from class CommissionEmployee.
3 Public Class BasePlusCommissionEmployee
4 Inherits CommissionEmployee
5
( 1 of 3 )
5 6 Private baseSalaryValue As Decimal ' base salary per week
7 8 ' six-argument constructor
9 Public Sub New(ByVal first As String, ByVal last As String, _
10 ByVal ssn As String, ByVal sales As Decimal, _ 11 ByVal rate As Double, ByVal salary As Decimal) 12 13 ' use MyBase reference to CommissionEmployee constructor explicitly 14 MyBase.New(first, last, ssn, sales, rate) y
15 BaseSalary = salary ' validate and store base salary 16 End Sub ' New 17
2009 Pearson Education, Inc. All rights reserved.
Fig. 11.11 | BasePlusCommissionEmployee inherits Protected instance variables from CommissionEmployee. (Part 1 of 3.)
48Outline
18 ' property BaseSalary 19 Public Property BaseSalary() As Decimal 20 Get 21 Return baseSalaryValue 22 End Get
BasePlusCommissionEmployee.vb
( 2 of 3 )22 End Get 23 24 Set(ByVal salary As Decimal) 25 If salary < 0D Then ' validate base salary 26 baseSalaryValue = 0D 27 El
( 2 of 3 )
27 Else 28 baseSalaryValue = salary 29 End If 30 End Set 31 End Property ' BaseSalary 32 33 ' calculate earnings 34 Public Overrides Function CalculateEarnings() As Decimal 35 Return baseSalaryValue + ( _ 36 Convert.ToDecimal(commissionRateValue) * grossSalesValue)
Calculating the earnings of a BasePlusCommissionEmployee37 End Function ' CalculateEarnings
Employee.
Fig. 11.11 | BasePlusCommissionEmployee inherits Protected instance variables from CommissionEmployee. (Part 2 of 3.)
2009 Pearson Education, Inc. All rights reserved.
49Outline
38 39 ' return String representation of BasePlusCommissionEmployee object 40 Public Overrides Function ToString() As String
BasePlusCommissionEmployee.vb
( 3 of 3 )41 Return ("base-plus-commission employee: " & firstNameValue & _ 42 " " & lastNameValue & vbNewLine & "social security number: " & _ 43 socialSecurityNumberValue & vbNewLine & "gross sales: " & _ 44 String.Format("{0:C}", grossSalesValue) & vbNewLine & _ 45 "commission rate: " & String.Format("{0:F}", _
Outputting the information of a BasePlusCommissionEmployee.
( 3 of 3 )
g ( { } , _
46 commissionRateValue) & vbNewLine & "base salary: " & _ 47 String.Format("{0:C}", baseSalaryValue)) 48 End Function ' ToString 49 End Class ' BasePlusCommissionEmployee
Fig. 11.11 | BasePlusCommissionEmployee inherits Protected instance variables from CommissionEmployee. (Part 3 of 3.)
2009 Pearson Education, Inc. All rights reserved.
50Outline
• Figure 11.12 tests the modified classes.
1 ' Fig. 11.12: BasePlusCommissionEmployeeTest.vb
2 ' Testing class BasePlusCommissionEmployee.
BasePlusCommissionEmployeeTest.vb
( 1 of 2 )
Figure 11.12 tests the modified classes.
g p y
3 Module BasePlusCommissionEmployeeTest
4 Sub Main()
5 ' instantiate BasePlusCommissionEmployee object
6 Dim employee As New BasePlusCommissionEmployee( _
7 "Bob" "Lewis" "333 33 3333" 5000D 0 04 300D)
( 1 of 2 )
7 Bob , Lewis , 333-33-3333 , 5000D, 0.04, 300D)
8 9 ' get base-salaried commission employee data
10 Console.WriteLine("Employee information obtained by properties:" _ 11 & vbNewLine & "First name is " & employee.FirstName & _ 12 vbNewLine & "Last name is " & employee.LastName & vbNewLine & _ 13 "Social Security Number is " & employee.SocialSecurityNumber) 14 Console.WriteLine("Gross sales is {0:C}", employee.GrossSales) 15 Console.WriteLine("Commission rate is {0:F}", _ 16 employee.CommissionRate) p y )
17 Console.WriteLine("Base salary is {0:C}", employee.BaseSalary) 18
Fig. 11.12 | Protected base class members inherited into derived class l C i i l (P t 1 f 2 )
2009 Pearson Education, Inc. All rights reserved.
BasePlusCommissionEmployee. (Part 1 of 2.)
5119 employee.BaseSalary = 1000D ' set base salary 20 21 ' get new employee information 22 Console WriteLine(vbNewLine &
Outline
22 Console.WriteLine(vbNewLine & _ 23 "Updated employee information obtained by ToString: " & _ 24 vbNewLine & employee.ToString() & vbNewLine) 25 26 ' display the employee's earnings 27 Console WriteLine("Employee's earnings: {0:C}" &
BasePlusCommissionEmployeeTest.vb
( 2 of 2 )27 Console.WriteLine( Employee's earnings: {0:C} & _
28 employee.CalculateEarnings()) 29 End Sub ' Main 30 End Module ' BasePlusCommissionEmployeeTest
Employee information obtained by properties:
( 2 of 2 )
Employee information obtained by properties:
First name is Bob
Last name is Lewis
Social Security Number is 333-33-3333
Gross sales is $5,000.00
Commission rate is 0.04
Base salary is $300.00
Updated employee information obtained by ToString:
base-plus-commission employee: Bob Lewis
social security number: 333-33-3333
gross sales: $5,000.00 gross sales: $5,000.00
commission rate: 0.04
base salary: $1,000.00
Employee's earnings: $1,200.00
2009 Pearson Education, Inc. All rights reserved.
Fig. 11.12 | Protected base class members inherited into derivedclass BasePlusCommissionEmployee. (Part 2 of 2.)
52
11.4 Relationship between Base Classes and Derived Classes (Cont )and Derived Classes (Cont.)
• Using Protected instance variables creates potential problemspotential problems.
– The derived class can set an inherited variable to an invalid value.
– Derived classes should depend only on the base class services and not on data implementation.We should be able to change the base class implementation– We should be able to change the base class implementation while still providing the same services.
S ft E i i Ob ti 11 5Software Engineering Observation 11.5Use the Protected access modifier on a method when abase class is to provide the method to its derived classes but
2009 Pearson Education, Inc. All rights reserved.
base class is to provide the method to its derived classes butnot to other clients.
53Outline
• Class CommissionEmployee (Fig. 11.13) now declares Private instance variables and provides
1 ' Fig. 11.13: CommmissionEmployee.vb
2 ' CommissionEmployee class represents a commission employee.
CommmissionEmployee.vb
( 1 of 6 )
declares Private instance variables and provides Public properties.
p y p p y
3 Public Class CommissionEmployee
4 Private firstNameValue As String ' first name
5 Private lastNameValue As String ' last name
6 Private socialSecurityNumberValue As String ' social security number
7 Private grossSalesValue As Decimal ' gross weekly sales
( 1 of 6 )
Using Privateinstance variables.
7 Private grossSalesValue As Decimal gross weekly sales
8 Private commissionRateValue As Double ' commission percentage
9 10 ' five-argument constructor 11 Public Sub New(ByVal first As String, ByVal last As String, _ 12 ByVal ssn As String ByVal sales As Decimal ByVal rate As Double) 12 ByVal ssn As String, ByVal sales As Decimal, ByVal rate As Double) 13 14 ' implicit call to Object constructor occurs here 15 FirstName = first 16 LastName = last 17 SocialSec rit N mber ssn 17 SocialSecurityNumber = ssn 18 GrossSales = sales ' validate and store gross sales 19 CommissionRate = rate ' validate and store commission rate 20 End Sub ' New 21
2009 Pearson Education, Inc. All rights reserved.
Fig. 11.13 | CommissionEmployee class uses properties tomanipulate its Private instance variables. (Part 1 of 6.)
54
22 ' t Fi tN
Outline
22 ' property FirstName 23 Public Property FirstName() As String 24 Get 25 Return firstNameValue 26 End Get
CommmissionEmployee.vb
( 2 of 6 )27 28 Set(ByVal first As String) 29 firstNameValue = first ' no validation 30 End Set 31 End Property ' FirstName
( 2 of 6 )
31 End Property FirstName
32 33 ' property LastName 34 Public Property LastName() As String 35 Get 36 R t l tN V l 36 Return lastNameValue 37 End Get 38 39 Set(ByVal last As String) 40 lastNameValue = last ' no validation 41 End Set 42 End Property ' LastName
Fig. 11.13 | CommissionEmployee class uses properties toi l t it i t i t i bl (P t 2 f 6 )
2009 Pearson Education, Inc. All rights reserved.
manipulate its Private instance variables. (Part 2 of 6.)
55Outline
43 44 ' property SocialSecurityNumber 45 Public Property SocialSecurityNumber() As String 46 Get
CommmissionEmployee.vb
( 3 of 6 )46 Get 47 Return socialSecurityNumberValue 48 End Get 49 50 Set(ByVal ssn As String) 51 i l i b l ' lid i
( 3 of 6 )
51 socialSecurityNumberValue = ssn ' no validation 52 End Set 53 End Property ' SocialSecurityNumber 54 55 ' property GrossSales 56 Public Property GrossSales() As Decimal 57 Get 58 Return grossSalesValue 59 End Get 6060
Fig. 11.13 | CommissionEmployee class uses properties tomanipulate its Private instance variables. (Part 3 of 6.)
2009 Pearson Education, Inc. All rights reserved.
56Outline
61 Set(ByVal sales As Decimal) 62 If sales < 0D Then ' validate gross sales
CommmissionEmployee.vb
( 4 of 6 )g
63 grossSalesValue = 0D 64 Else 65 grossSalesValue = sales 66 End If 67 End Set
( 4 of 6 )
67 End Set 68 End Property ' GrossSales 69 70 ' property CommissionRate 71 Public Property CommissionRate() As Double 72 Get 73 Return commissionRateValue 74 End Get 75
Fig. 11.13 | CommissionEmployee class uses properties tomanipulate its Private instance variables. (Part 4 of 6.)
2009 Pearson Education, Inc. All rights reserved.
57Outline
76 Set(ByVal rate As Double) 77 If rate > 0.0 AndAlso rate < 1.0 Then ' validate rate 78 commissionRateValue = rate
CommmissionEmployee.vb
( 5 of 6 )79 Else 80 commissionRateValue = 0.0 81 End If 82 End Set 83 End Property ' CommissionRate
( 5 of 6 )
83 d ope ty Co ss o ate
84 85 ' calculate earnings 86 Public Overridable Function CalculateEarnings() As Decimal 87 Return Convert.ToDecimal(CommissionRate) * GrossSales 88 End Function ' CalculateEarnings
CalculateEarningscalculates a CommissionEmployee’s
i88 End Function CalculateEarnings
89
earnings.
Fig. 11.13 | CommissionEmployee class uses properties tomanipulate its Private instance variables (Part 5 of 6 )manipulate its Private instance variables. (Part 5 of 6.)
2009 Pearson Education, Inc. All rights reserved.
58Outline
90 ' return String representation of CommissionEmployee object 91 Public Overrides Function ToString() As String
CommmissionEmployee.vb
( 6 of 6 )92 Return ("commission employee: " & FirstName & " " & _ 93 LastName & vbNewLine & "social security number: " & _ 94 SocialSecurityNumber & vbNewLine & "gross sales: " & _ 95 String.Format("{0:C}", GrossSales) & vbNewLine & _ 96 "commission rate: " & String.Format("{0:F}", CommissionRate))
Outputting a CommissionEmployee’s properties.
( 6 of 6 )
97 End Function ' ToString 98 End Class ' CommissionEmployee
Fig. 11.13 | CommissionEmployee class uses properties toi l t it i i t i bl (P t 6 f 6 )manipulate its Private instance variables. (Part 6 of 6.)
2009 Pearson Education, Inc. All rights reserved.
59
Software Engineering Observation 11.6Declaring base class instance variables PrivateDeclaring base class instance variables Private(as opposed to Protected) enables the base classimplementation of these instance variables to changewithout affecting derived class implementationswithout affecting derived class implementations.
Error-Prevention Tip 11.1Error Prevention Tip 11.1When possible, do not include Protected instance variables in abase class. Instead, include non-Private properties and methods th t f ll Private i t i bl Thi illthat carefully access Private instance variables. This will ensure that objects of the derived classes of this base class maintain consistent states of the base class instance variables.
2009 Pearson Education, Inc. All rights reserved.
60Outline
• Derived class BasePlusCommissionEmployee(Fig 11 14) inherits CommissionEmployee’s non-
1 ' Fig. 11.14: BasePlusCommissionEmployee.vb
BasePlusCommissionEmployee.vb
( 1 of 4 )
(Fig. 11.14) inherits CommissionEmployee s nonPrivate properties and methods.
g p y
2 ' BasePlusCommissionEmployee inherits from class CommissionEmployee.
3 Public Class BasePlusCommissionEmployee
4 Inherits CommissionEmployee
5 6 Private baseSalaryValue As Decimal ' base salary per week
( 1 of 4 )
6 Private baseSalaryValue As Decimal base salary per week
7 8 ' six-argument constructor
9 Public Sub New(ByVal first As String, ByVal last As String, _
10 ByVal ssn As String, ByVal sales As Decimal, _ 11 ByVal rate As Double, ByVal salary As Decimal) 12 13 ' use MyBase reference to CommissionEmployee constructor explicitly 14 MyBase.New(first, last, ssn, sales, rate) 15 BaseSalary = salary ' validate and store base salary y y y
16 End Sub ' New 17
Fig. 11.14 | BasePlusCommissionEmployee class Inherits
2009 Pearson Education, Inc. All rights reserved.
g | p yCommissionEmployee, which provides only Private
instance variables. (Part 1 of 3.)
61Outline
18 ' property BaseSalary 19 Public Property BaseSalary() As Decimal 20 Get 21 Return baseSalaryValue
BasePlusCommissionEmployee.vb
( 2 of 4 )22 End Get 23 24 Set(ByVal salary As Decimal) 25 If salary < 0D Then ' validate base salary 26 baseSalaryValue = 0D
( 2 of 4 )
26 baseSalaryValue = 0D 27 Else 28 baseSalaryValue = salary 29 End If 30 End Set
d ' l 31 End Property ' BaseSalary 32 33 ' calculate earnings 34 Public Overrides Function CalculateEarnings() As Decimal 35 Return BaseSalary + MyBase.CalculateEarnings()
Adding base salary to aCommissionEmployee’s earnings.
36 End Function ' CalculateEarnings
earnings.
Fig. 11.14 | BasePlusCommissionEmployee class InheritsCommissionEmployee, which provides only Private
2009 Pearson Education, Inc. All rights reserved.
CommissionEmployee, which provides only Privateinstance variables. (Part 2 of 3.)
62Outline
BasePlusCommissionEmployee.vb
( 3 of 4 )37 38 ' return String representation of BasePlusCommissionEmployee object 39 Public Overrides Function ToString() As String 40 Return ("base-plus-" & MyBase.ToString() & vbNewLine & _ 41 "base salary: " & String Format("{0:C}" BaseSalary))
Adding the base salary property to the CommissionEmployee’s
( 3 of 4 )
41 base salary: & String.Format( {0:C} , BaseSalary))
42 End Function ' ToString 43 End Class ' BasePlusCommissionEmployee
output.
Fig. 11.14 | BasePlusCommissionEmployee class Inheritsg | p yCommissionEmployee, which provides only Private
instance variables. (Part 3 of 3.)
2009 Pearson Education, Inc. All rights reserved.
63Outline
BasePlusCommissionEmployee.vb
( 4 of 4 )
Common Programming Error 11.3Wh b l th d i idd i d i d
( 4 of 4 )
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 MyBaseand a dot (.) separator causes the derived class method to call itself, usually resulting in infinite recursion.to call itself, usually resulting in infinite recursion.
2009 Pearson Education, Inc. All rights reserved.
64Outline
• Figure 11.15 performs a test of theBasePlusCommissionEmployee object
1 ' Fig. 11.15: BasePlusCommissionEmployeeTest.vb
2 ' Testing class BasePlusCommissionEmployee.
BasePlusCommissionEmployeeTest.vb
( 1 of 2 )
BasePlusCommissionEmployee object.
g p y
3 Module BasePlusCommissionEmployeeTest
4 Sub Main()
5 ' instantiate BasePlusCommissionEmployee object
6 Dim employee As New BasePlusCommissionEmployee( _
7 "Bob" "Lewis" "333-33-3333" 5000D 0 04 300D)
( 1 of 2 )
7 Bob , Lewis , 333-33-3333 , 5000D, 0.04, 300D)
8 9 ' get base-salaried commission employee data
10 Console.WriteLine("Employee information obtained by properties:" _ 11 & vbNewLine & "First name is " & employee.FirstName & _
b i & " i " & l & b i &12 vbNewLine & "Last name is " & employee.LastName & vbNewLine & _ 13 "Social Security Number is " & employee.SocialSecurityNumber) 14 Console.WriteLine("Gross sales is {0:C}", employee.GrossSales) 15 Console.WriteLine("Commission rate is {0:F}", _ 16 employee.CommissionRate) 17 Console.WriteLine("Base salary is {0:C}", employee.BaseSalary)
Fig. 11.15 | Base class Private instance variables are accessible to aderived class via the Public or Protected properties and
2009 Pearson Education, Inc. All rights reserved.
methods inherited by the derived class. (Part 1 of 2.)
6518 19 employee.BaseSalary = 1000D ' set base salary 20 21 ' get new employee information 22 Console WriteLine(vbNewLine &
Outline
22 Console.WriteLine(vbNewLine & _ 23 "Updated employee information obtained by ToString: " & _ 24 vbNewLine & employee.ToString() & vbNewLine) 25 26 ' display the employee's earnings 27 Console WriteLine("Employee's earnings: {0:C}" &
BasePlusCommissionEmployeeTest.vb
( 2 of 2 )27 Console.WriteLine( Employee s earnings: {0:C} & _
28 employee.CalculateEarnings()) 29 End Sub ' Main 30 End Module ' BasePlusCommissionEmployeeTest
Employee information obtained by properties:
( 2 of 2 )
Employee information obtained by properties:
First name is Bob
Last name is Lewis
Social Security Number is 333-33-3333
Gross sales is $5,000.00
Commission rate is 0.04
Base salary is $300.00
Updated employee information obtained by ToString:
base-plus-commission employee: Bob Lewis
social security number: 333-33-3333
gross sales: $5,000.00 gross sales: $5,000.00
commission rate: 0.04
base salary: $1,000.00
Employee's earnings: $1,200.00
2009 Pearson Education, Inc. All rights reserved.
Fig. 11.15 | Base class Private instance variables are accessible
to a derived class via the Public or Protected propertiesand methods inherited by the derived class. (Part 1 of 2.)
66Outline• Instantiating a derived class object begins a chain of
constructor calls.
1 ' Fig. 11.16: CommissionEmployee.vb
CommissionEmployee.vb
( 1 of 6 )
• Our next example redeclares class CommissionEmployee(Fig. 11.16) with the constructor printing a message.
2 ' CommissionEmployee class represents a commission employee.
3 Public Class CommissionEmployee
4 Private firstNameValue As String ' first name
5 Private lastNameValue As String ' last name
6 Private socialSecurityNumberValue As String ' social security number
( 1 of 6 )
y g y
7 Private grossSalesValue As Decimal ' gross weekly sales
8 Private commissionRateValue As Double ' commission percentage
9 10 ' five-argument constructor 11 Public Sub New(ByVal first As String ByVal last As String 11 Public Sub New(ByVal first As String, ByVal last As String, _ 12 ByVal ssn As String, ByVal sales As Decimal, ByVal rate As Double) 13 14 ' implicit call to Object constructor occurs here 15 FirstName = first 16 LastName = last 17 SocialSecurityNumber = ssn 18 GrossSales = sales ' validate and store gross sales 19 CommissionRate = rate ' validate and store commission rate
2009 Pearson Education, Inc. All rights reserved.
Fig. 11.16 | CommissionEmployee’s constructoroutputs text. (Part 1 of 6.)
67
20 Console.WriteLine(vbNewLine & _
Outline
21 "CommissionEmployee constructor:" & vbNewLine & "{0}", Me) 22 End Sub ' New 23 24 ' property FirstName 25 Public Property FirstName() As String
CommissionEmployee.vb
( 2 of 6 )26 Get 27 Return firstNameValue 28 End Get 29 30 Set(ByVal first As String)
When this class’s constructor executes, the object’s information
( 2 of 6 )
30 Set(ByVal first As String) 31 firstNameValue = first ' no validation 32 End Set 33 End Property ' FirstName 34 35 ' property LastName
the object s information is printed.
Outputting Me35 ' property LastName 36 Public Property LastName() As String 37 Get 38 Return lastNameValue 39 End Get
implicitly invokes the ToString method
40 41 Set(ByVal last As String) 42 lastNameValue = last ' no validation 43 End Set 44 End Property ' LastName
2009 Pearson Education, Inc. All rights reserved.
Fig. 11.16 | CommissionEmployee’s constructoroutputs text. (Part 2 of 6.)
68Outline
45 46 ' property SocialSecurityNumber
CommissionEmployee.vb
( 3 of 6 )p p y y
47 Public Property SocialSecurityNumber() As String 48 Get 49 Return socialSecurityNumberValue 50 End Get 51
( 3 of 6 )
51 52 Set(ByVal ssn As String) 53 socialSecurityNumberValue = ssn ' no validation 54 End Set 55 End Property ' SocialSecurityNumber 56 57 ' property GrossSales 58 Public Property GrossSales() As Decimal 59 Get 60 Return grossSalesValue g
61 End Get 62
Fig. 11.16 | CommissionEmployee’s constructor
2009 Pearson Education, Inc. All rights reserved.
outputs text. (Part 3 of 6.)
69Outline
63 Set(ByVal sales As Decimal) 64 If sales < 0D Then ' validate gross sales
CommissionEmployee.vb
( 4 of 6 )g
65 grossSalesValue = 0D 66 Else 67 grossSalesValue = sales 68 End If 69 End Set
( 4 of 6 )
69 End Set 70 End Property ' GrossSales 71 72 ' property CommissionRate 73 Public Property CommissionRate() As Double 74 Get 75 Return commissionRateValue 76 End Get
Fig 11 16 | CommissionEmployee’s constructorFig. 11.16 | CommissionEmployee s constructoroutputs text. (Part 4 of 6.)
2009 Pearson Education, Inc. All rights reserved.
70Outline
77 78 Set(ByVal rate As Double)
CommissionEmployee.vb
( 5 of 6 )( y )
79 If rate > 0.0 AndAlso rate < 1.0 Then ' validate rate 80 commissionRateValue = rate 81 Else 82 commissionRateValue = 0.0 83 End If
( 5 of 6 )
83 End If 84 End Set 85 End Property ' CommissionRate 86 87 ' calculate earnings 88 Public Overridable Function CalculateEarnings() As Decimal 89 Return Convert.ToDecimal(CommissionRate) * GrossSales 90 End Function ' CalculateEarnings
Fig 11 16 | CommissionEmployee’s constructorFig. 11.16 | CommissionEmployee s constructoroutputs text. (Part 5 of 6.)
2009 Pearson Education, Inc. All rights reserved.
71Outline
91 92 ' return String representation of CommissionEmployee object
CommissionEmployee.vb
( 6 of 6 )g p p y j
93 Public Overrides Function ToString() As String 94 Return ("commission employee: " & FirstName & " " & _ 95 LastName & vbNewLine & "social security number: " & _ 96 SocialSecurityNumber & vbNewLine & "gross sales: " & _ 97 String Format("{0:C}" GrossSales) & vbNewLine &
( 6 of 6 )
97 String.Format( {0:C} , GrossSales) & vbNewLine & _
98 "commission rate: " & String.Format("{0:F}", CommissionRate)) 99 End Function ' ToString 100 End Class ' CommissionEmployee
Fig. 11.16 | CommissionEmployee’s constructoroutputs text. (Part 6 of 6.)
2009 Pearson Education, Inc. All rights reserved.
72Outline
• The BasePlusCommissionEmployee (Fig. 11.17)
1 ' Fig. 11.17: BasePlusCommissionEmployee.vb
2 ' BasePlusCommissionEmployee inherits from class CommissionEmployee.
BasePlusCommissionEmployee.vb
( 1 of 3 )
constructor also outputs text when invoked.
p y p y
3 Public Class BasePlusCommissionEmployee
4 Inherits CommissionEmployee
5 6 Private baseSalaryValue As Decimal ' base salary per week
7
( 1 of 3 )
7 8 ' six-argument constructor
9 Public Sub New(ByVal first As String, ByVal last As String, _
10 ByVal ssn As String, ByVal sales As Decimal, _ 11 ByVal rate As Double, ByVal salary As Decimal) 1212 13 ' use MyBase reference to CommissionEmployee constructor explicitly 14 MyBase.New(first, last, ssn, sales, rate) 15 BaseSalary = salary ' validate and store base salary 16 Console.WriteLine(vbNewLine & _ 17 "BasePlusCommissionEmployee constructor:" &
When this class’s constructor executes the object’s information is17 BasePlusCommissionEmployee constructor: & _
18 vbNewLine & "{0}", Me) 19 End Sub ' New
executes, the object s information is printed.
Fig. 11.17 | BasePlusCommissionEmployee’s constructor outputs text. (Part 1 of 3.)
2009 Pearson Education, Inc. All rights reserved.
Fig. 11.17 | BasePlusCommissionEmployee s constructor outputs text. (Part 1 of 3.)
73Outline
20 21 ' property BaseSalary
BasePlusCommissionEmployee.vb
( 2 of 3 )p p y y
22 Public Property BaseSalary() As Decimal 23 Get 24 Return baseSalaryValue 25 End Get 26
( 2 of 3 )
26 27 Set(ByVal salary As Decimal) 28 If salary < 0D Then ' validate base salary 29 baseSalaryValue = 0D 30 Else 31 baseSalaryValue = salary 32 End If 33 End Set 34 End Property ' BaseSalary
Fig. 11.17 | BasePlusCommissionEmployee’s constructor outputs text. (Part 2 of 3.)
2009 Pearson Education, Inc. All rights reserved.
74Outline
35 36 ' calculate earnings
BasePlusCommissionEmployee.vb
( 3 of 3 )g
37 Public Overrides Function CalculateEarnings() As Decimal 38 Return BaseSalary + MyBase.CalculateEarnings() 39 End Function ' CalculateEarnings 40 41 ' return String representation of BasePlusCommissionEmployee object
( 3 of 3 )
41 return String representation of BasePlusCommissionEmployee object
42 Public Overrides Function ToString() As String 43 Return ("base-plus-" & MyBase.ToString() & vbNewLine & _ 44 "base salary: " & String.Format("{0:C}", BaseSalary)) 45 End Function ' ToString 46 End Class ' BasePlusCommissionEmployee
Fig. 11.17 | BasePlusCommissionEmployee’s constructor outputs text. (Part 3 of 3.)
2009 Pearson Education, Inc. All rights reserved.
75Outline• Figure 11.18 demonstrates the order in which constructors are
called.
Constructor.vb
( 1 of 2 )
• BasePlusCommissionEmployee’s version of the ToString method is called from CommissionEmployee’s constructor, so the base salary is
i i i li d i h d 1 ' Fig. 11.18: Constructor.vb
2 ' Display order in which base class and derived class constructors
3 ' and finalizers are called.
not yet initialized in the second output.
4 Module Constructor
5 Sub Main()
6 Dim employee1 As New CommissionEmployee( _
7 "Bob", "Lewis", "333-33-3333", 5000D, 0.04)
8 Console WriteLine() 8 Console.WriteLine()
9 10 Dim employee2 As New BasePlusCommissionEmployee( _ 11 "Lisa", "Jones", "555-55-5555", 2000D, 0.06, 800D) 12 End Sub ' Main
d d l '13 End Module ' Constructor
Fig. 11.18 | Constructor call order using Me. (Part 1 of 2.)
2009 Pearson Education, Inc. All rights reserved.
76Outline
CommissionEmployee constructor:
commission employee: Bob Lewis
social security number: 333-33-3333
gross sales: $5,000.00
Constructor.vb
( 2 of 2 )
commission rate: 0.04
CommissionEmployee constructor:
base-plus-commission employee: Lisa Jones
social security number: 555 55 5555 social security number: 555-55-5555
gross sales: $2,000.00
commission rate: 0.06
base salary: $0.00
BasePlusCommissionEmployee constructor:
base-plus-commission employee: Lisa Jones
social security number: 555-55-5555
gross sales: $2,000.00
commission rate: 0.06
base salary: $800.00
Fig. 11.18 | Constructor call order using Me. (Part 2 of 2.)
2009 Pearson Education, Inc. All rights reserved.
g | g ( )
77
11.5 Constructors in Derived Classes (Cont )(Cont.)
A method call ith MyClass al a s in okes the• A method call with MyClass always invokes the version of the method defined in that particular class.
• Replace Me in line 21 with• Replace Me in line 21 withMyClass.ToString()
• CommissionEmployee’s ToString will be executed by the class’s constructor.
2009 Pearson Education, Inc. All rights reserved.
78
11.5 Constructors in Derived Classes (Cont )(Cont.)
• Now execute the program. The output is shown in Fig. 11.19.
CommissionEmployee constructor:
commission employee: Bob Lewis
social security number: 333-33-3333
gross sales: $5,000.00
commission rate: 0.04
CommissionEmployee constructor:
commission employee: Lisa Jones
i l i bsocial security number: 555-55-5555
gross sales: $2,000.00
commission rate: 0.06
BasePlusCommissionEmployee constructor:
b l i i l Li J base-plus-commission employee: Lisa Jones
social security number: 555-55-5555
gross sales: $2,000.00
commission rate: 0.06
base salary: $800.00
2009 Pearson Education, Inc. All rights reserved.
Fig. 11.19 | Constructor call order using MyClass.
79
11.6 Software Engineering with InheritanceInheritance
• Extending classes to meet our needs by includingExtending classes to meet our needs by including additional members and by overriding base class members is a useful practice.
• Independent software vendors (ISVs) develop proprietary classes for sale or license and make them available to users in MSIL format.
2009 Pearson Education, Inc. All rights reserved.
80
11.6 Software Engineering with Inheritance (Cont )Inheritance (Cont.)
Software Engineering Observation 11.7Despite the fact that inheriting from a class does not require access to the class’s source code, developers often insist on seeing the source code to see how theoften insist on seeing the source code to see how the class is implemented. They want to ensure that they are extending a solid class that performs well and is implemented securely.
2009 Pearson Education, Inc. All rights reserved.
81
11.6 Software Engineering with Inheritance (Cont )
Software Engineering Observation 11.8
Inheritance (Cont.)
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 instance variables and methods and place them in a base class. Then the designer should use inheritance to develop derived classes, specializing them with capabilities beyond those inherited from the base class.p y
Performance Tip 11.1If derived classes are larger than they need to be (i.e., contain too much functionality), memory and pro-cessing resources may be wasted. Extend the base class that contains the functionality that is closest to what you need.
2009 Pearson Education, Inc. All rights reserved.
y
82
11.6 Software Engineering with Inheritance (Cont )Inheritance (Cont.)
Performance Tip 11.11If derived classes are larger than they need to be(i.e., contain too much functionality), memory and pro cessing resources may be wasted Extend the basepro-cessing resources may be wasted. Extend the base class that contains the functionality that is closest to what you need.
2009 Pearson Education, Inc. All rights reserved.
83
11.7 Class Object
• All classes inherit seven methods from class Object (Fig. 11.20).
Method Description
Equals Compares two objects for equality; returns True if they are equal and False otherwise.
Finalize This Protected method is called by the garbage collector on an y g gobject just before the garbage collector reclaims the object’s memory.
GetHashCode A hashtable is a data structure that relates one object, called the key to another object called the valuekey, to another object, called the value.
Fig. 11.20 | Object methods that are inherited by all classes. (Part 1 of 2.)
2009 Pearson Education, Inc. All rights reserved.
84
11.7 Class Object (Cont.)
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. The implementation of this method performs a shallow copy—instance variable values in one object are copied into another object of the same typeanother object of the same type.
ReferenceEquals This Shared method returns True if two objects are the same instance.
ToString This method returns a String representation of an object.
Fig. 11.20 | Object methods that are inherited by all classes. (Part 2 of 2.)
2009 Pearson Education, Inc. All rights reserved.
85
11.8 Friend Members
• A class’s Friend members can be accessed only by code in the same assembly.
• To access a non-Shared Friend member within the same assembly, create an object of the class that declares the Friend member.Y i d b h i h d• You can access a Friend member that is Sharedvia the name of the class that declares the Friendmembermember.
• Protected Friend members are accessible both from code in the same assembly and by
2009 Pearson Education, Inc. All rights reserved.
both from code in the same assembly and by subclasses.