vb 2008 htp 12 [read-only]personal.kent.edu/~asamba/tech46330/chap12.pdf · • suppose we design a...

75
1 12 12 12 12 Object-Oriented Programming: Polymorphism 2009 Pearson Education, Inc. All rights reserved.

Upload: others

Post on 22-Sep-2020

2 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

1

12121212Object-Oriented

Programming:Polymorphism

2009 Pearson Education, Inc. All rights reserved.

Page 2: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

2

O Ri t l th llOne Ring to rule them all,One Ring to find them,One Ring to bring them allOne Ring to bring them alland in the darkness bind them.

– J. R. R. Tolkien

General propositions do notdecide concrete cases.

– Oliver Wendell Holmes

2009 Pearson Education, Inc. All rights reserved.

Page 3: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

3

A hil h f i i t t d ’tA philosopher of imposing stature doesn’tthink in a vacuum. Even his most abstract ideas are, to some extent, conditioned by what is or isare, to some extent, conditioned by what is or isnot known in the time when he lives.

– Alfred North Whitehead

Why art thou cast down, O my soul?– Psalms 42:5

2009 Pearson Education, Inc. All rights reserved.

Page 4: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

4

OBJECTIVESOBJECTIVESIn this chapter you will learn:

Wh t l hi i What polymorphism is. To use overridden methods to effect

l hipolymorphism. To distinguish between abstract and concrete

classesclasses. To declare abstract methods to create abstract

classesclasses.

2009 Pearson Education, Inc. All rights reserved.

Page 5: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

5

OBJECTIVESOBJECTIVES How polymorphism makes systems extensible

and maintainableand maintainable. To determine an object’s type at execution

timetime. To declare and implement interfaces.

2009 Pearson Education, Inc. All rights reserved.

Page 6: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

6

12.1 Introduction12.2 Polymorphic Video Game12.3 Demonstrating Polymorphic Behavior12.4 Abstract Classes and Methods12.5 Case Study: Payroll System Class Hierarchy

Using PolymorphismUsing Polymorphism12.6 NotOverridable Methods and NotInheritable

Classes12.7 Case Study: Creating and Using Interfaces12.8 (Optional) Software Engineering Case Study: ( p ) g g y

Incorporating Inheritance and Polymorphism into the ATM System

2009 Pearson Education, Inc. All rights reserved.

Page 7: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

7

12.1 Introduction

• Polymorphism enables us to “program in the general.”• New classes can be added to an inheritance hierarchy

with little or no modification to the general portions of the programthe program.

2009 Pearson Education, Inc. All rights reserved.

Page 8: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

8

12.2 Polymorphic Video Game

• Suppose we design a video game with objects of many types inheriting from class SpaceObjecttypes, inheriting from class SpaceObject

• The screen manager makes the same method call, Draw for each objectDraw, for each object.

• Each derived class implements Draw in a manner appropriate to that classappropriate to that class.

2009 Pearson Education, Inc. All rights reserved.

Page 9: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

9

12.2 Polymorphic Video Game (Cont.)

Software Engineering Observation 12.1Software that invokes polymorphic behavior is i f j iindependent of the object types to which messages are sent. New object types that can respond to existing method calls can be incorporated into a system withoutmethod calls can be incorporated into a system without requiring modification

2009 Pearson Education, Inc. All rights reserved.

Page 10: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

10Outline• To perform a derived class-specific operation, the

program must downcast a base class reference.

1 ' Fig. 12.1: PolymorphismTest.vb

2 ' Assigning base class and derived class references to base class and

PolymorphismTest.vb

( 1 of 3 )

• Figure 12.1 shows three ways to use base class and derived class variables..

3 ' derived class variables.

4 Module PolymorphismTest

5 Sub Main()

6 Dim commissionEmployee1 As CommissionEmployee

7 Dim basePlusCommissionEmployee As BasePlusCommissionEmployee

( 1 of 3 )

CommissionEmployeeobject assigned to a CommissionEmployee 7 Dim basePlusCommissionEmployee As BasePlusCommissionEmployee

8 9 ' assign base class reference to base class variable

10 commissionEmployee1 = New CommissionEmployee( _ 11 "Sue", "Jones", "222-22-2222", 10000D, 0.06) 12

p yvariable.

12 13 ' assign derived class reference to derived class variable 14 basePlusCommissionEmployee = New BasePlusCommissionEmployee( _ 15 "Bob", "Lewis", "333-33-3333", 5000D, 0.04, 300D) 16

BasePlusCommission­Employee object assigned to a BasePlusCommissionEmployee variable.

17 ' invoke ToString on base class object using base class varixable 18 Console.WriteLine("Call CommissionEmployee's ToString with " & _ 19 "base class reference to base class object: " & vbNewLine & _ 20 commissionEmployee1.ToString() & vbNewLine)

2009 Pearson Education, Inc. All rights reserved.

Fig. 12.1 | Assigning base class and derived class references to base class and

derived class variables. (Part 1 of 3.)

Page 11: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

11Outline

21 22 ' invoke ToString on derived class object using

PolymorphismTest.vb

( 2 of 3 )g j g

23 ' derived class variable 24 Console.WriteLine("Call BasePlusCommissionEmployee's ToString " & _ 25 "with derived class reference to derived class object: " & _ 26 vbNewLine & basePlusCommissionEmployee.ToString() & vbNewLine) 27

( 2 of 3 )

27 28 ' assign derived class reference to base class variable 29 Dim commissionEmployee2 As CommissionEmployee = _ 30 basePlusCommissionEmployee 31

BasePlusCommission­Employee object assigned to a Commission­Employeevariable.

32 ' invoke ToString on derived class object using base class variable 33 Console.WriteLine("Call BasePlusCommissionEmployee's ToString " & _ 34 "with base class reference to derived class object: " & _ 35 vbNewLine & commissionEmployee2.ToString()) 36 End Sub ' Main

Calling ToStringpolymorphically.

37 End Module ' PolymorphismTest 37 End Module ' PolymorphismTest

Fig. 12.1 | Assigning base class and derived class references to base class and

2009 Pearson Education, Inc. All rights reserved.

derived class variables. (Part 2 of 3.)

Page 12: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

12Outline

PolymorphismTest.vb

( 3 of 3 )( 3 of 3 )

Call CommissionEmployee's ToString with base class reference to base class object: commission employee: Sue Jones social security number: 222-22-2222 gross sales: 10,000.00 g ,commission rate: 0.06 Call BasePlusCommissionEmployee's ToString with derived class reference to derived class object: 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: 300.00 Call BasePlusCommissionEmployee's ToString with base class reference to derived class object: commission employee: Bob Lewis social security number: 333 33 3333 social security number: 333-33-3333 gross sales: 5,000.00 commission rate: 0.04 base salary: 300.00

Fi 12 1 A i i b l d d i d l f t b l d

2009 Pearson Education, Inc. All rights reserved.

Fig. 12.1 | Assigning base class and derived class references to base class and derived class variables. (Part 3 of 3.)

Page 13: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

13

12.4 Abstract Classes and Methods

• Abstract classes are incomplete classes which cannot be instantiatedbe instantiated.

• In the Shape hierarchy, we could derive concrete classes from abstract class TwoDimensionalShapeclasses from abstract class TwoDimensionalShape.

• A programmer can use an abstract base class as a parameter typeparameter type.

• These methods can be passed an object of any concrete class that inherits the base classclass that inherits the base class.

2009 Pearson Education, Inc. All rights reserved.

Page 14: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

14

12.4 Abstract Classes and Methods (Cont.)(Cont.) • Make a class abstract by declaring it with MustInheritMustInherit.

• Abstract methods have keyword MustOverride in th i d l titheir declarations:

Public MustOverride Sub Draw() ' abstract method

• A class that contains any abstract methods must be d l d b t t ldeclared as an abstract class.

2009 Pearson Education, Inc. All rights reserved.

Page 15: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

15

12.4 Abstract Classes and Methods (Cont.)(Cont.)

Software Engineering Observation 12.2An abstract class typically contains one or more abstract

i i if imethods that derived classes must override if the derived classes are to be concrete. The instance variables and concrete methods of an abstract class are subject to theconcrete methods of an abstract class are subject to the normal rules of inheritance.

2009 Pearson Education, Inc. All rights reserved.

Page 16: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

16

12.4 Abstract Classes and Methods (Cont.)(Cont.)

Common Programming Error 12.1Attempting to instantiate an object of an abstract

i i iclass is a compilation error.

Common Programming Error 12.2Failure to implement a base class’s abstractFailure to implement a base class s abstract methods in a derived class is a compilation errorunless the derived class is also declared MustInherit.

2009 Pearson Education, Inc. All rights reserved.

Page 17: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

17

12.4 Abstract Classes and Methods (C t )(Cont.)

• It is common to declare an iterator class that canIt is common to declare an iterator class that can represent all the objects in a collection, such as an array or a List.

• An ArrayList of objects of class TwoDimensionalShape could contain objects from derived classes Square, Circle, Triangleand so on.

2009 Pearson Education, Inc. All rights reserved.

Page 18: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

18

12.5 Case Study: Payroll System Class Hierarchy Using PolymorphismHierarchy Using Polymorphism

• We create an enhanced employee hierarchy to solve the following problem:A company wants to implement an application that performs its payroll calculations on a weekly basis. Salaried employees are paid a fixed weekly salary, h l l id b th h d ihourly employees are paid by the hour and receive overtime pay (1.5 times the regular hourly salary), commission employees are paid a percentage of theircommission employees are paid a percentage of their sales, and other employees receive a base salary plus a percentage of their sales.

2009 Pearson Education, Inc. All rights reserved.

Page 19: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

19

12.5 Case Study: Payroll System Class Hierarchy Using Polymorphism (Cont.)Hierarchy Using Polymorphism (Cont.)

• The UML class diagram in Fig. 12.2 shows an inheritance hi hhierarchy.

• Note that abstract class name Employee is italicized.

Fig 12 2 | Employee hierarchy UML class diagram

2009 Pearson Education, Inc. All rights reserved.

Fig. 12.2 | Employee hierarchy UML class diagram.

Page 20: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

20

12.5 Case Study: Payroll System Class Hierarchy Using Polymorphism (Cont.)

12.5.1 Creating Abstract Base Class Employee

Hierarchy Using Polymorphism (Cont.)

g p y

• Class Employee will provide methods CalculateEarnings and ToString, and g g,properties that manipulate instance variables.

• We declare CalculateEarnings as gMustOverride so that each derived class provides an appropriate implementation.

• Each derived class of Employee overrides method ToString to include the employee’s type.

2009 Pearson Education, Inc. All rights reserved.

Page 21: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

21

12.5 Case Study: Payroll System Class Hierarchy Using Polymorphism (Cont )• The diagram in Fig. 12.3 shows polymorphic variations of

the Employee class’s methods.

Hierarchy Using Polymorphism (Cont.)

p y

2009 Pearson Education, Inc. All rights reserved.

Fig. 12.3 | Polymorphic interface for the Employee hierarchy classes.

Page 22: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

22Outline

• Class Employee is shown in Fig. 12.4.

1 ' Fig. 12.4: Employee.vb

2 ' Employee abstract base class.

Employee.vb

( 1 of 3 )

Class Employee is shown in Fig. 12.4.

p y

3 Public MustInherit Class Employee

4 Private firstNameValue As String

5 Private lastNameValue As String

6 Private socialSecurityNumberValue As String

7

Using MustInherit makes the class abstract.

7 8 ' three-argument constructor

9 Public Sub New(ByVal first As String, ByVal last As String, _

10 ByVal ssn As String) 11 FirstName = first 12 LastName = last 13 SocialSecurityNumber = ssn 14 End Sub ' New 15 16 ' property FirstName p p y

17 Public Property FirstName() As String 18 Get 19 Return firstNameValue 20 End Get

2009 Pearson Education, Inc. All rights reserved.

Fig. 12.4 | Employee abstract base class. (Part 1 of 3.)

Page 23: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

23Outline

21 22 Set(ByVal first As String)

Employee.vb

( 2 of 3 )( y g)

23 firstNameValue = first 24 End Set 25 End Property ' FirstName 26 27 ' property LastName 27 property LastName

28 Public Property LastName() As String 29 Get 30 Return lastNameValue 31 End Get 32 33 Set(ByVal last As String) 34 lastNameValue = last 35 End Set 36 End Property ' LastName p y

37

Fig. 12.4 | Employee abstract base class. (Part 2 of 3.)

2009 Pearson Education, Inc. All rights reserved.

Page 24: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

24Outline

38 ' property SocialSecurityNumber 39 Public Property SocialSecurityNumber() As String 40 Get 41 Return socialSecurityNumberValue

Employee.vb

( 3 of 3 )41 Return socialSecurityNumberValue 42 End Get 43 44 Set(ByVal ssn As String) 45 socialSecurityNumberValue = ssn 46 End Set 47 End Property ' SocialSecurityNumber 48 49 ' return String representation of Employee object 50 Public Overrides Function ToString() As String g() g

51 Return (String.Format("{0} {1}", FirstName, LastName) & _ 52 vbNewLine & "social security number: " & SocialSecurityNumber) 53 End Function ' ToString 54 55 ' abstract method overridden by derived class 55 abstract method overridden by derived class

56 Public MustOverride Function CalculateEarnings() As Decimal 57 End Class ' Employee

Using MustOverridemakes the method abstract.

Fig. 12.4 | Employee abstract base class. (Part 3 of 3.)

2009 Pearson Education, Inc. All rights reserved.

g | p y ( )

Page 25: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

25Outline

• Class SalariedEmployee (Fig. 12.5) is a concrete

1 ' Fig. 12.5: SalariedEmployee.vb

2 ' SalariedEmployee class inherits Employee

SalariedEmployee.vb

( 1 of 2 )

Class SalariedEmployee (Fig. 12.5) is a concrete class which inherits an abstract class.

p y p y

3 Public Class SalariedEmployee

4 Inherits Employee

5 6 Private weeklySalaryValue As Decimal ' employee's weekly salary

7

( 1 of 2 )

Class SalariedEmployeeinherits from abstract class 7

8 ' four-argument constructor

9 Public Sub New(ByVal first As String, ByVal last As String, _

10 ByVal ssn As String, ByVal salary As Decimal) 11 MyBase.New(first, last, ssn) ' pass to Employee constructor

inherits from abstract class Employee.

Calling the Employeeconstructor12 WeeklySalary = salary ' validate and store salary

13 End Sub ' New 14 15 ' property WeeklySalary 16 Public Property WeeklySalary() As Decimal

constructor.

p y y y

17 Get 18 Return weeklySalaryValue 19 End Get 20

2009 Pearson Education, Inc. All rights reserved.

Fig. 12.5 | SalariedEmployee class derived from classEmployee. (Part 1 of 2.)

Page 26: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

26Outline

21 Set(ByVal salary As Decimal) 22 If salary < 0D Then ' validate salary

SalariedEmployee.vb

( 2 of 2 )y y

23 weeklySalaryValue = 0D 24 Else 25 weeklySalaryValue = salary 26 End If 27 End Set

( 2 of 2 )

27 End Set 28 End Property ' WeeklySalary 29 30 ' calculate earnings; override abstract method CalculateEarnings 31 Public Overrides Function CalculateEarnings() As Decimal Overriding

l l i32 Return WeeklySalary 33 End Function ' CalculateEarnings 34 35 ' return String representation of SalariedEmployee object 36 Public Overrides Function ToString() As String

Calculate­Earnings makes SalariedEmployee a concrete class.

Outputting the employee’s g g

37 Return ("salaried employee: " & MyBase.ToString() & vbNewLine & _ 38 String.Format("weekly salary {0:C}", WeeklySalary)) 39 End Function ' ToString 40 End Class ' SalariedEmployee

type, information produced by Employee’s ToStringmethod and the WeeklySalary property.

2009 Pearson Education, Inc. All rights reserved.

Fig. 12.5 | SalariedEmployee class derived from classEmployee. (Part 2 of 2.)

Page 27: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

27Outline

• Class HourlyEmployee (Fig. 12.6) also inherits class

1 ' Fig. 12.6: HourlyEmployee.vb

HourlyEmployee.vb

( 1 of 4 )

Class HourlyEmployee (Fig. 12.6) also inherits class Employee.

2 ' HourlyEmployee class inherits Employee.

3 Public Class HourlyEmployee

4 Inherits Employee

5 6 Private wageValue As Decimal ' wage per hour

Class HourlyEmployee inherits from abstract class Employee.

6 Private wageValue As Decimal wage per hour

7 Private hoursValue As Decimal ' hours worked for week

8 9 ' five-argument constructor

10 Public Sub New(ByVal first As String, ByVal last As String, _ 11 ByVal ssn As String ByVal hourlyWage As Decimal 11 ByVal ssn As String, ByVal hourlyWage As Decimal, _ 12 ByVal hoursWorked As Decimal) 13 MyBase.New(first, last, ssn) ' pass to Employee constructor 14 Wage = hourlyWage ' validate and store hourly wage 15 Hours = hoursWorked ' validate and store hours worked

Calling the Employeeconstructor.

16 End Sub ' New 17

Fig. 12.6 | HourlyEmployee class derived from class Employee. (Part 1 of 4.)

2009 Pearson Education, Inc. All rights reserved.

Page 28: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

28Outline

18 ' property Wage 19 Public Property Wage() As Decimal 20 Get

HourlyEmployee.vb

( 2 of 4 )

21 Return wageValue 22 End Get 23 24 Set(ByVal hourlyWage As Decimal) 25 If hourlyWage < 0D Then ' validate hourly wage 25 If hourlyWage < 0D Then validate hourly wage

26 wageValue = 0D 27 Else 28 wageValue = hourlyWage 29 End If 30 End Set 31 End Property ' Wage 32 33 ' property Hours 34 Public Property Hours() As Decimal p y

35 Get 36 Return hoursValue 37 End Get 38

2009 Pearson Education, Inc. All rights reserved.

Fig. 12.6 | HourlyEmployee class derived from class Employee. (Part 2 of 4.)

Page 29: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

29Outline

39 Set(ByVal hoursWorked As Decimal) 40 If (hoursWorked >= 0.0) AndAlso (hoursWorked <= 168.0) Then

HourlyEmployee.vb

( 3 of 4 )( ) ( )

41 hoursValue = hoursWorked ' valid weekly hours 42 Else 43 hoursValue = 0 44 End If 45 End Set 45 End Set 46 End Property ' Hours 47 48 ' calculate earnings; override abstract method CalculageEarnings 49 Public Overrides Function CalculateEarnings() As Decimal 50 If Hours <= 40 Then ' no overtime 51 Return Wage * Hours 52 Else 53 Return 40 * Wage + ((Hours - 40) * Wage * 1.5D) 54 End If

Overriding Calculate­Earnings makes HourlyEmployee a concreteclass.

55 End Function ' CalculateEarnings

Fig. 12.6 | HourlyEmployee class derived from class Employee. (Part 3 of 4.)

2009 Pearson Education, Inc. All rights reserved.

Page 30: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

30Outline

56 57 ' return String representation of HourlyEmployee object

HourlyEmployee.vb

( 4 of 4 )g p y p y j

58 Public Overrides Function ToString() As String 59 Return ("hourly employee: " & MyBase.ToString() & vbNewLine & _ 60 String.Format("hourly wage: {0:C}; hours worked: {1}", _ 61 Wage, Hours)) 62 End Function ' ToString

Outputting the employee’s type, information produced by Employee’s ToString method and more specific information.

62 End Function ToString

63 End Class ' HourlyEmployee

Fig. 12.6 | HourlyEmployee class derived from class Employee. (Part 4 of 4.)

2009 Pearson Education, Inc. All rights reserved.

Page 31: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

31Outline

• Class CommissionEmployee (Fig. 12.7) is another

1 ' Fig. 12.7: CommissionEmployee.vb

2 ' CommissionEmployee class inherits Employee.

3 P bli Cl C i i E l

CommissionEmployee.vb

( 1 of 3 )

extension of Employee.

3 Public Class CommissionEmployee

4 Inherits Employee

5 6 Private grossSalesValue As Decimal

7 Private commissionRateValue As Double

( 1 of 3 )Class CommissionEmployeeinherits from abstract class Employee.

8 9 ' five-argument constructor

10 Public Sub New(ByVal first As String, ByVal last As String, _ 11 ByVal ssn As String, ByVal sales As Decimal, ByVal rate As Double) 12 MyBase.New(first, last, ssn) ' pass to Employee constructor Calling the Employee12 MyBase.New(first, last, ssn) pass to Employee constructor

13 GrossSales = sales ' validate and store gross sales 14 CommissionRate = rate ' validate and store commission rate 15 End Sub ' New 16 17 ' t G S l

g p yconstructor.

17 ' property GrossSales 18 Public Property GrossSales() As Decimal 19 Get 20 Return grossSalesValue 21 End Get

2009 Pearson Education, Inc. All rights reserved.

Fig. 12.7 | CommissionEmployee class derived from Employee. (Part 1 of 3.)

Page 32: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

32Outline

22 23 Set(ByVal sales As Decimal)

CommissionEmployee.vb

( 2 of 3 )( y )

24 If sales < 0 Then ' validate gross sales 25 grossSalesValue = 0 26 Else 27 grossSalesValue = sales 28 End If

( 2 of 3 )

28 End If 29 End Set 30 End Property ' GrossSales 31 32 ' property CommissionRate 33 Public Property CommissionRate() As Double 34 Get 35 Return commissionRateValue 36 End Get 37

Fig. 12.7 | CommissionEmployee class derived from Employee. (Part 2 of 3.)

2009 Pearson Education, Inc. All rights reserved.

Page 33: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

33Outline

38 Set(ByVal rate As Decimal) 39 If rate > 0.0 AndAlso rate < 1.0 Then ' validate commission rate 40 commissionRateValue = rate

CommissionEmployee.vb

( 3 of 3 )41 Else 42 commissionRateValue = 0 43 End If 44 End Set 45 End Property ' CommissionRate

( 3 of 3 )

45 End Property CommissionRate

46 47 ' calculate earnings; override abstract method CalculateEarnings 48 Public Overrides Function CalculateEarnings() As Decimal 49 Return Convert.ToDecimal(CommissionRate) * GrossSales

Overriding Calculate­Earnings makes HourlyEmployee a concrete50 End Function ' CalculateEarnings

51 52 ' return String representation of CommissionEmployee object 53 Public Overrides Function ToString() As String 54 Return ("commission employee: " & MyBase.ToString() & vbNewLine & _

HourlyEmployee a concrete class.

Outputting the employee’s type, information produced

55 String.Format("gross sales: {0:C}; commission rate: {1}", _ 56 GrossSales, CommissionRate)) 57 End Function ' ToString 58 End Class ' CommissionEmployee

yp , pby Employee’s ToString method and more specific information.

2009 Pearson Education, Inc. All rights reserved.

Fig. 12.7 | CommissionEmployee class derived from Employee. (Part 3 of 3.)

Page 34: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

34Outline

• BasePlusCommissionEmployee (Fig. 12.8) inherits CommissionEmployee and therefore is

1 ' Fig. 12.8: BasePlusCommissionEmployee.vb

2 ' BasePlusCommissionEmployee class inherits CommissionEmployee.

BasePlusCommissionEmployee.vb

( 1 of 2 )

p yan indirect derived class of Employee.

2 BasePlusCommissionEmployee class inherits CommissionEmployee.

3 Public Class BasePlusCommissionEmployee

4 Inherits CommissionEmployee

5 6 Private baseSalaryValue As Decimal ' base salary

7

( 1 of 2 )Class BasePlusCommissionEmployeeinherits 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 Decimal, ByVal salary As Decimal)

l12 MyBase.New(first, last, ssn, sales, rate) 13 BaseSalary = salary 14 End Sub ' New 15 16 ' property BaseSalary

Calling the Employeeconstructor.

16 property BaseSalary

17 Public Property BaseSalary() As Decimal 18 Get 19 Return baseSalaryValue 20 End Get

2009 Pearson Education, Inc. All rights reserved.

Fig. 12.8 | BasePlusCommissionEmployee derived from CommissionEmployee. (Part 1 of 2.)

Page 35: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

35Outline

21 22 Set(ByVal salary As Decimal) 23 If salary < 0 Then ' validate salary 24 baseSalaryValue = 0 25 l

BasePlusCommissionEmployee.vb

( 2 of 2 )25 Else 26 baseSalaryValue = salary 27 End If 28 End Set 29 End Property ' BaseSalary

( 2 of 2 )

30 31 ' calculate earnings; override method CalculateEarnings 32 Public Overrides Function CalculateEarnings() As Decimal 33 Return BaseSalary + MyBase.CalculateEarnings() 34 End Function ' CalculateEarnings 34 End Function CalculateEarnings

35 36 ' return String representation of BasePlusCommissionEmployee object 37 Public Overrides Function ToString() As String 38 Return ("base-salaried " & MyBase.ToString() & _ 39 i (" b l {0 }" l ))

Outputting the employee’s type, information produced by Employee’ ToString th d39 String.Format("; base salary: {0:C}", BaseSalary))

40 End Function ' ToString 41 End Class ' BasePlusCommissionEmployee

Employee’s ToString method and more specific information.

Fig. 12.8 | BasePlusCommissionEmployee derived from

2009 Pearson Education, Inc. All rights reserved.

Fig. 12.8 | BasePlusCommissionEmployee derived from CommissionEmployee. (Part 2 of 2.)

Page 36: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

36Outline

• The program in Fig. 12.9 creates an object of each f h f l

1 ' Fig. 12.9: PayrollSystemTest.vb

2 ' Employee hierarchy test program.

PayrollSystemTest.vb

( 1 of 6 )

of the four concrete classes.

p y y p g

3 Module PayrollSystemTest

4 Sub Main()

5 ' create derived class objects

6 Dim salariedEmployee As New SalariedEmployee( _

7 "John" "Smith" "111 11 1111" 800)

( 1 of 6 )

7 John , Smith , 111-11-1111 , 800)

8 Dim hourlyEmployee As New HourlyEmployee( _

9 "Karen", "Price", "222-22-2222", 16.75D, 40)

10 Dim commissionEmployee As New CommissionEmployee( _ 11 "Sue", "Jones", "333-33-3333", 10000, 0.06)

Creating objects of each of the four Employeederived classes.

12 Dim basePlusCommissionEmployee As New BasePlusCommissionEmployee( _ 13 "Bob", "Lewis", "444-44-4444", 5000, 0.04, 300) 14 15 ' display each employee’s info non-polymorphically 16 Console.WriteLine("Employees processed individually:" & vbNewLine) ( p y p y )

17 Console.WriteLine(salariedEmployee.ToString() & vbNewLine & _ 18 String.Format("earned: {0:C}", _ 19 salariedEmployee.CalculateEarnings()) & vbNewLine)

Fi 12 9 | E l l hi h t t (P t 1 f 6 )

2009 Pearson Education, Inc. All rights reserved.

Fig. 12.9 | Employee class hierarchy test program. (Part 1 of 6.)

Page 37: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

37Outline

20 Console.WriteLine(hourlyEmployee.ToString() & vbNewLine & _ 21 String.Format("earned: {0:C}", _

PayrollSystemTest.vb

( 2 of 6 )g ( { } , _

22 hourlyEmployee.CalculateEarnings()) & vbNewLine) 23 Console.WriteLine(commissionEmployee.ToString() & vbNewLine & _ 24 String.Format("earned: {0:C}", _ 25 commissionEmployee.CalculateEarnings()) & vbNewLine) 26 Console WriteLine(basePlusCommissionEmployee ToString() &

( 2 of 6 )

26 Console.WriteLine(basePlusCommissionEmployee.ToString() & _ 27 vbNewLine & String.Format("earned: {0:C}", _ 28 basePlusCommissionEmployee.CalculateEarnings()) & vbNewLine) 29 30 ' create four-element Employee array 31 Dim employees() As Employee = {salariedEmployee, hourlyEmployee, _ 32 commissionEmployee, basePlusCommissionEmployee} 33 34 Console.WriteLine("Employees processed polymorphically:" & _ 35 vbNewLine)

Storing Employeeobjects in an array.

)

36

Fig. 12.9 | Employee class hierarchy test program. (Part 2 of 6.)

2009 Pearson Education, Inc. All rights reserved.

Page 38: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

38Outline

37 ' polymorphically process each element in array employees 38 For Each currentEmployee In employees

PayrollSystemTest.vb

( 3 of 6 )p y p y

39 Console.WriteLine(currentEmployee.ToString()) 40 41 ' determine if currentEmployee is a BasePlusCommissionEmployee 42 If (TypeOf currentEmployee Is BasePlusCommissionEmployee) Then 43

( 3 of 6 )

43 44 ' downcast Employee reference to BasePlusCommissionEmployee 45 Dim employee As BasePlusCommissionEmployee = _ 46 TryCast(currentEmployee, BasePlusCommissionEmployee) 47 48 employee.BaseSalary *= 1.1D 49 Console.WriteLine(String.Format( _ 50 "new base salary with 10% increase is: {0:C}", _ 51 employee.BaseSalary)) 52 End If 53

Fig. 12.9 | Employee class hierarchy test program. (Part 3 of 6.)

2009 Pearson Education, Inc. All rights reserved.

Page 39: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

39Outline

PayrollSystemTest.vb

( 4 of 6 )54 Console.Write(String.Format("earned {0:C}", _ 55 currentEmployee.CalculateEarnings()) & vbNewLine & vbNewLine) 56 Next 57 58 ' get type name of each object in employees array

( 4 of 6 )

58 get type name of each object in employees array

59 For i As Integer = 0 To employees.Length - 1 60 Console.WriteLine(String.Format("Employee {0} is a {1}", _ 61 i, employees(i).GetType().FullName)) 62 Next 63 d b ' i

Outputting Employee object types polymorphically.

63 End Sub ' Main 64 End Module ' PayrollSystemTest

Fig. 12.9 | Employee class hierarchy test program. (Part 4 of 6.)

2009 Pearson Education, Inc. All rights reserved.

Page 40: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

40

Outline

Employees processed individually:

salaried employee: John Smith

social security number: 111-11-1111

weekly salary $800.00

d $800 00

PayrollSystemTest.vb

( 5 of 6 )earned: $800.00

hourly employee: Karen Price

social security number: 222-22-2222

hourly wage: $16.75; hours worked: 40

earned: $670 00

( 5 of 6 )

earned: $670.00

commission employee: Sue Jones

social security number: 333-33-3333

gross sales: $10,000.00; commission rate: 0.06

earned: $600.00

base-salaried commission employee: Bob Lewis

social security number: 444-44-4444

gross sales: $5,000.00; commission rate: 0.04; base salary: $300.00

earned: $600.00

( i d ) (continued on next page...)

Fig. 12.9 | Employee class hierarchy test program. (Part 5 of 6.)

2009 Pearson Education, Inc. All rights reserved.

Page 41: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

41

(continued from previous page…) Employees processed polymorphically:

Outline

salaried employee: John Smith

social security number: 111-11-1111

weekly salary $800.00

earned $800.00

hourly employee: Karen Price

PayrollSystemTest.vb

( 6 of 6 )hourly employee: Karen Price

social security number: 222-22-2222

hourly wage: $16.75; hours worked: 40

earned $670.00

commission employee: Sue Jones

( 6 of 6 )

p y

social security number: 333-33-3333

gross sales: $10,000.00; commission rate: 0.06

earned $600.00

base-salaried commission employee: Bob Lewis

social security number: 444-44-4444

gross sales: $5,000.00; commission rate: 0.04; base salary: $300.00

new base salary with 10% increase is: $330.00

earned: $530.00

Employee 0 is a PayrollSystem SalariedEmployee Employee 0 is a PayrollSystem.SalariedEmployee

Employee 1 is a PayrollSystem.HourlyEmployee

Employee 2 is a PayrollSystem.CommissionEmployee

Employee 3 is a PayrollSystem.BasePlusCommissionEmployee

2009 Pearson Education, Inc. All rights reserved.

Fig. 12.9 | Employee class hierarchy test program. (Part 6 of 6.)

Page 42: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

42

12.5 Case Study: Payroll System Class Hierarchy Using Polymorphism (Cont )Hierarchy Using Polymorphism (Cont.)

• The output polymorphically displays the earningsand types of different Employee objects.

Using Expression TypeOf …Is to DetermineObject Type

f• TypeOf... Is tests for a particular type.

2009 Pearson Education, Inc. All rights reserved.

Page 43: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

43

12.5 Case Study: Payroll System Class Hierarchy Using Polymorphism (Cont )Hierarchy Using Polymorphism (Cont.)

Using TryCast to Downcast from a Base Class to a Derived Class Type• TryCast attempts to downcast a base class type to a derived

l tclass type.• If the object is not an instance of the derived class, TryCast

returns Nothing.returns Nothing.• GetType returns a Type object which contains information

about an object’s type.

2009 Pearson Education, Inc. All rights reserved.

Page 44: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

44

12.5 Case Study: Payroll System Class Hierarchy Using Polymorphism (Cont.)Hierarchy Using Polymorphism (Cont.)

Common Programming Error 12.3Common Programming Error 12.3Assigning a base class variable to a derived class variable (without an explicit cast) is a compilation error.( p ) p

Error-Prevention Tip 12.1Before performing a downcast, use the Typeof...Isexpression to ensure that the object is indeed an object of an appropriate derived class type Then usean appropriate derived class type. Then use DirectCast to downcast from the base class type to the derived class type.

2009 Pearson Education, Inc. All rights reserved.

yp

Page 45: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

45

12.6 NotOverridable Methods and h i blNotInheritable Classes

• A method that is declared NotOverridable cannot be overridden.

• An inherited method can be declared NotOverridable i d i d l t tNotOverridable in a derived class to prevent further inheritance.

• A class that is declared NotInheritable cannot• A class that is declared NotInheritable cannot be a base class.

Common Programming Error 12 4Common Programming Error 12.4Attempting to inherit a NotInheritable class is a compilation error.

2009 Pearson Education, Inc. All rights reserved.

compilation error.

Page 46: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

46

12.7 Case Study: Creating and Using Interfaces• A Visual Basic interface describes a set of methods

that can be called on an object.• An interface declaration begins with keyword Interface and can contain abstract methods and properties.

• To use an interface, a concrete class must specify that it Implements the interface and must implement each methodeach method.

2009 Pearson Education, Inc. All rights reserved.

Page 47: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

47

12.7 Case Study: Creating and Using Interfaces (Cont )Interfaces (Cont.)

Common Programming Error 12 5Common Programming Error 12.5It is a compilation error to explicitly declare interface methods Public

Common Programming Error 12 6

methods Public.

Common Programming Error 12.6In Visual Basic, an Interface should be declaredonly as Public or Friend; the declaration of anonly as Public or Friend; the declaration of an Interface as Private or Protected is only possible within another type.

2009 Pearson Education, Inc. All rights reserved.

Page 48: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

48

12.7 Case Study: Creating and Using Interfaces (Cont )Interfaces (Cont.)

Common Programming Error 12.7Failing to implement any method of an interface in aFailing to implement any method of an interface in a concrete class that Implements the interface results in a syntax error indicating that the class must be declared

h iMustInherit.

2009 Pearson Education, Inc. All rights reserved.

Page 49: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

49

12.7 Case Study: Creating and Using Interfaces (Cont )

12.7.1 Developing an IPayable Hierarchy

Interfaces (Cont.)

• Interface IPayable contains method GetPaymentAmount, which returns a Decimal, and ToString.

• Classes Invoice and Employee will implement interface IPayable.

• A program will be able to invoke i lGetPaymentAmount on Invoices, Employees

and any future objects.

2009 Pearson Education, Inc. All rights reserved.

Page 50: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

50

12.7 Case Study: Creating and Using Interfaces (Cont )

Good Programming Practice 12.1

Interfaces (Cont.)

When declaring a method in an interface, choose a method name that describes the method’s purpose in a

l b h h d bgeneral manner, because the method may be implemented by many unrelated classes.

2009 Pearson Education, Inc. All rights reserved.

Page 51: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

51

12.7 Case Study: Creating and Using Interfaces (Cont )• The UML class diagram in Fig. 12.10 shows the class and

i f hi h

Interfaces (Cont.)

interface hierarchy.• The UML expresses the interface implementation through an

association known as a realizationassociation known as a realization.

2009 Pearson Education, Inc. All rights reserved.

Fig. 12.10 | IPayable interface hierarchy UML class diagram.

Page 52: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

52Outline

• Interface IPayable (Fig. 12.11) contains abstract

1 ' Fig. 12.11: IPayable.vb

2 ' IPayable interface declaration.

IPayable.vb

Interface IPayable (Fig. 12.11) contains abstractmethod GetPaymentAmount.

y

3 Public Interface IPayable

4 Function GetPaymentAmount() As Decimal ' calculate payment

5 End Interface ' IPayable

An interface declaration.

blFig. 12.11 | IPayable interface declaration.

2009 Pearson Education, Inc. All rights reserved.

Page 53: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

53

• Invoice (Fig. 12.12) represents a simple invoice that

Outline

1 ' Fig. 12.12: Invoice.vb

2 ' Invoice class implements IPayable.

Invoice (Fig. 12.12) represents a simple invoice thatcontains billing information for only one kind of part. Invoice.vb

( 1 of 5 )p y

3 Public Class Invoice

4 Implements IPayable

5 6 Private partNumberValue As String

7 Private partDescriptionValue As String

Invoice implements the IPayable interface.

7 Private partDescriptionValue As String

8 Private quantityValue As Integer

9 Private pricePerItemValue As Decimal

10 11 ' four-argument constructor 12 Public Sub New(ByVal part As String, ByVal description As String, _ 13 ByVal count As Integer, ByVal price As Decimal) 14 PartNumber = part 15 PartDescription = description 16 Quantity = count ' validate quantity y q y

17 PricePerItem = price ' validate price per item 18 End Sub ' New 19

i bl

2009 Pearson Education, Inc. All rights reserved.

Fig. 12.12 | Invoice class that implements interface IPayable. (Part 1 of 5.)

Page 54: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

54

20 ' property PartNumber

Outline

21 Public Property PartNumber() As String 22 Get 23 Return partNumberValue 24 End Get 25

Invoice.vb

( 2 of 5 )

26 Set(ByVal part As String) 27 partNumberValue = part 28 End Set 29 End Property ' PartNumber 3030 31 ' property PartDescription 32 Public Property PartDescription() As String 33 Get 34 Return partDescriptionValue 35 End Get 36 37 Set(ByVal description As String) 38 partDescriptionValue = description 39 End Set 39 d Set

40 End Property ' PartDescription

Fig. 12.12 | Invoice class that implements interface IPayable. (Part 2 of 5.)

2009 Pearson Education, Inc. All rights reserved.

Page 55: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

55

41

Outline

41 42 ' property Quantity 43 Public Property Quantity() As Integer 44 Get 45 Return quantityValue 46 End Get

Invoice.vb

( 3 of 5 )46 End Get 47 48 Set(ByVal count As Integer) 49 If count < 0 Then ' validate quantity 50 quantityValue = 0 51 Else 52 quantityValue = count 53 End If 54 End Set 55 End Property ' Quantity p y Q y

56 57 ' property PricePerItem 58 Public Property PricePerItem() As Decimal 59 Get 60 Return pricePerItemValue 60 Return pricePerItemValue 61 End Get

Fig. 12.12 | Invoice class that implements interface IPayable. (Part 3 of 5.)

2009 Pearson Education, Inc. All rights reserved.

Page 56: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

56Outline

62 63 Set(ByVal price As Decimal)

Invoice.vb

( 4 of 5 )( y p )

64 If price < 0 Then ' validate price 65 pricePerItemValue = 0 66 Else 67 pricePerItemValue = price 68 End If 68 End If 69 End Set 70 End Property ' PricePerItem 71 72 ' function required to carry out contract with interface IPayable 73 Public Function GetPaymentAmount() As Decimal _ 74 Implements IPayable.GetPaymentAmount 75 Return Quantity * PricePerItem ' calculate total cost 76 End Function ' GetPaymentAmount

Implementing IPayable’s GetPaymentAmount.

Fig. 12.12 | Invoice class that implements interface IPayable. (Part 4 of 5.)

2009 Pearson Education, Inc. All rights reserved.

Page 57: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

57Outline

77 78 ' return String representation of Invoice object

Invoice.vb

( 5 of 5 )g p j

79 Public Overrides Function ToString() As String _ 80 Return ("invoice:" & vbNewLine & "part number: " & PartNumber & _ 81 "(" & PartDescription & ")" & vbNewLine & "quantity: " & _ 82 Quantity & vbNewLine & _ 83 String Format("price per item: {0:C}" PricePerItem))

ToString returns the String representation of an Invoice object.83 String.Format("price per item: {0:C}", PricePerItem))

84 End Function ' ToString 85 End Class ' Invoice

j

Fig. 12.12 | Invoice class that implements interface IPayable. (Part 5 of 5.)Fig. 12.12 | Invoice class that implements interface IPayable. (Part 5 of 5.)

2009 Pearson Education, Inc. All rights reserved.

Page 58: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

58

• Figure 12.13 contains the modified Employee class.

Outline

1 ' Fig. 12.13: Employee.vb

2 ' Employee abstract base class implements IPayable.

Figure 12.13 contains the modified Employee class.Employee.vb

( 1 of 3 )p y p y

3 Public MustInherit Class Employee

4 Implements IPayable

5 6 Private firstNameValue As String

7 Private lastNameValue As String

Employee implements the IPayable interface.

7 Private lastNameValue As String

8 Private socialSecurityNumberValue As String

9 10 ' three-argument constructor 11 Public Sub New(ByVal first As String, ByVal last As String, _ 12 ByVal ssn As String) 13 FirstName = first 14 LastName = last 15 SocialSecurityNumber = ssn 16 End Sub ' New 16 End Sub New

17

Fig. 12.13 | Employee class that implements interface IPayable. (Part 1 of 3.)

2009 Pearson Education, Inc. All rights reserved.

Page 59: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

59

18 ' property FirstName

Outline

19 Public Property FirstName() As String 20 Get 21 Return firstNameValue 22 End Get 23

Employee.vb

( 2 of 3 )

24 Set(ByVal first As String) 25 firstNameValue = first 26 End Set 27 End Property ' FirstName 2828 29 ' property LastName 30 Public Property LastName() As String 31 Get 32 Return lastNameValue 33 End Get 34 35 Set(ByVal last As String) 36 lastNameValue = last 37 End Set 3 d Set

38 End Property ' LastName

Fig. 12.13 | Employee class that implements interface IPayable. (Part 2 of 3.)

2009 Pearson Education, Inc. All rights reserved.

Page 60: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

60

39 40 ' property SocialSecurityNumber

Outline

p p y y

41 Public Property SocialSecurityNumber() As String 42 Get 43 Return socialSecurityNumberValue 44 End Get 45

Employee.vb

( 3 of 3 )45 46 Set(ByVal ssn As String) 47 socialSecurityNumberValue = ssn 48 End Set 49 End Property ' SocialSecurityNumber 50 51 ' return String representation of Employee object 52 Public Overrides Function ToString() As String _ 53 Return (String.Format("{0} {1}", FirstName, LastName) & _ 54 vbNewLine & "social security number: " & SocialSecurityNumber)

ToString overrides the version declared in base class Object

y y )

55 End Function ' ToString 56 57 ' Note: We do not implement IPayable function GetPaymentAmount here 58 Public MustOverride Function GetPaymentAmount() As Decimal _ 59 Implements IPayable GetPaymentAmount

Object.

IPayable’s GetPaymentAmount is still

59 Implements IPayable.GetPaymentAmount 60 End Class ' Employee

an abstract method.

Fig. 12.13 | Employee class that implements interface IPayable. (Part 3 of 3.)

2009 Pearson Education, Inc. All rights reserved.

Page 61: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

61

• Figure 12.14 contains a modified version ofSalariedEmployee

Outline

1 ' Fig. 12.14: SalariedEmployee.vb

2 ' SalariedEmployee class inherits Employee, which implements IPayable.

3 Public Class SalariedEmployee

SalariedEmployee.SalariedEmployee.vb

( 1 of 3 ) 4 Inherits Employee

5 6 Private weeklySalaryValue As Decimal

7 8 ' four-argument constructor

( 1 of 3 )

g

9 Public Sub New(ByVal first As String, ByVal last As String, _

10 ByVal ssn As String, ByVal salary As Decimal) 11 MyBase.New(first, last, ssn) ' pass to Employee constructor 12 WeeklySalary = salary ' validate and store salary 13 End Sub ' New 13 End Sub ' New 14 15 ' property WeeklySalary 16 Public Property WeeklySalary() As Decimal 17 Get 18 Return weeklySalaryValue 19 End Get 20

Fig 12 14 | SalariedEmployee class that implements interface IPayable

2009 Pearson Education, Inc. All rights reserved.

Fig. 12.14 | SalariedEmployee class that implements interface IPayable method GetPaymentAmount. (Part 1 of 2.)

Page 62: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

62

21 Set(ByVal salary As Decimal)

Outline

22 If salary < 0D Then ' validate salary 23 weeklySalaryValue = 0D 24 Else 25 weeklySalaryValue = salary 26 End If

SalariedEmployee.vb

( 2 of 3 )27 End Set 28 End Property ' WeeklySalary 29 30 ' calculate earnings; implements interface IPayable method 31 ' GetPaymentAmount that was MustOverride in base class Employee

( 2 of 3 )

31 GetPaymentAmount that was MustOverride in base class Employee

32 Public Overrides Function GetPaymentAmount() As Decimal 33 Return WeeklySalary 34 End Function ' GetPaymentAmount 35

Overriding Employee’s abstract GetPaymentAmount.

36 ' return String representation of SalariedEmployee object 37 Public Overrides Function ToString() As String 38 Return ("salaried employee: " & MyBase.ToString() & vnNewLine & _ 39 String.Format("weekly salary {0:C}", WeeklySalary)) 40 End Function ' ToString

ToString overrides the version declared in base class Employee.

g

41 End Class ' SalariedEmployee

Fig. 12.14 | SalariedEmployee class that implements interface IPayable method GetPaymentAmount. (Part 2 of 2.)

2009 Pearson Education, Inc. All rights reserved.

Page 63: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

63Outline

Software Engineering Observation 12 3Software Engineering Observation 12.3Inheritance and interfaces are similar in their implementation of the is-a relationship. An object

SalariedEmployee.vb

( 3 of 3 )p p jof a class that implements an interface may be thought of as an object of that interface type.

( 3 of 3 )

Software Engineering Observation 12.4If a parameter has a base class type, it can receive either a base class or derived class reference as an argument If a parameter has an interface type itargument. If a parameter has an interface type, it can receive a reference to an object of any class that implements the interface.

2009 Pearson Education, Inc. All rights reserved.

Page 64: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

64

• PayableInterfaceTest (Fig. 12.15) illustrates that

Outline

1 ' Fig 12 15: PayableInterfaceTest vb

PayableInterfaceTest (Fig. 12.15) illustrates thatinterface IPayable can be used to process a set ofInvoices and Employees polymorphically.

PayableInterfaceTest.vb

( 1 of 3 ) 1 Fig. 12.15: PayableInterfaceTest.vb

2 ' Testing interface IPayable.

3 Module PayableInterfaceTest

4 Sub Main()

5 ' create four-element IPayable array Declaring an array of

( 1 of 3 )

6 Dim payableObjects() As IPayable = New IPayable(3) {}

7 8 ' populate array with objects that implement IPayable

9 payableObjects(0) = New Invoice("01234", "seat", 2, 375D)

10 payableObjects(1) = New SalariedEmployee( _

Declaring an array of IPayables.

0 payab eObjects( ) e Sa a ed p oyee( _

11 "John", "Smith", "111-11-1111", 800D) 12 payableObjects(2) = New Invoice("56789", "tire", 4, 79.95D) 13 payableObjects(3) = New SalariedEmployee( _ 14 "Lisa", "Barnes", "888-88-8888", 1200D) 1515 16 Console.WriteLine( _ 17 "Invoices and Employees processed polymorphically:" & vbNewLine) 18

2009 Pearson Education, Inc. All rights reserved.

Fig. 12.15 | IPayable interface test program processing Invoices andEmployees polymorphically. (Part 1 of 3.)

Page 65: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

65Outline

19 ' generically process each element in array payableObjects 20 For Each currentPayable In payableObjects 21 ' output currentPayable and its appropriate payment amount

PayableInterfaceTest.vb

( 2 of 3 )22 Console.WriteLine(currentPayable.ToString() & vbNewLine & _ 23 String.Format("payment due: {0:C}", _ 24 currentPayable.GetPaymentAmount()) & vbNewLine) 25 Next 26 End Sub ' Main

The For statement processes IPayable

( 2 of 3 )

27 End Module ' PayableInterfaceTest

Invoices and Employees processed polymorphically:

invoice:

objects polymorphically.

part number: 01234(seat)

quantity: 2

price per item: $375.00

payment due: $750.00

salaried employee: John Smith sa a ed e p oyee Jo S t

social security number: 111-11-1111

weekly salary $800.00

payment due: $800.00

2009 Pearson Education, Inc. All rights reserved.

Fig. 12.15 | IPayable interface test program processing Invoices andEmployees polymorphically. (Part 2 of 3.)

Page 66: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

66Outline

PayableInterfaceTest.vb

( 3 of 3 )

invoice:

part number: 56789(tire)

quantity: 4

price per item: $79.95

d $ ( 3 of 3 )payment due: $319.80

salaried employee: Lisa Barnes

social security number: 888-88-8888

weekly salary $1,200.00

payment due: $1 200 00 payment due: $1,200.00

Fig. 12.15 | IPayable interface test program processing Invoices andEmployees polymorphically. (Part 3 of 3.)

Software Engineering Observation 12.5

p y p y p y ( )

Using a base class reference, you can polymorphically invoke any method specified in the base class declaration. Using an interface reference, you can polymorphically

2009 Pearson Education, Inc. All rights reserved.

g , y p y p yinvoke any method specified in the interface declaration.

Page 67: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

67

12.7 Case Study: Creating and Using Interfaces (Cont.)Interfaces (Cont.)

12.7.7 Common Interfaces of the .NET Framework Class LibraryClass Library

Interface Description

IComparable IComparable is used to allow objects to be compared to IComparable IComparable is used to allow objects to be compared to one another.

IComponent Implemented by any class that represents a component, including Graphical User Interface (GUI) controls.

bl IEnumerable Contains a GetEnumerator method, which returns an enumerator for the collection.

IEnumerator Used for iterating through the elements of a collection one element at a time.

2009 Pearson Education, Inc. All rights reserved.

Fig. 12.16 | Common interfaces of the .NET Class Library.

Page 68: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

68

12.8 Incorporating Inheritance and Polymorphism into the ATM System• Fig. 12.17 shows the attributes and operations of the

Polymorphism into the ATM System

three transaction classes.

Fig. 12.17 | Attributes and operations of classes BalanceInquiry,Withdrawal and Deposit.

2009 Pearson Education, Inc. All rights reserved.

p

Page 69: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

69

12.8 Incorporating Inheritance and Polymorphism into the ATM System (Cont )• The UML specifies a relationship called a generalization to

d l i h i

Polymorphism into the ATM System (Cont.)

model inheritance.• Figure 12.18 models the inheritance relationship between Transaction and its three derived classesTransaction and its three derived classes.

Fig 12 18 | Class diagram modeling the generalization (i e inheritance)

2009 Pearson Education, Inc. All rights reserved.

Fig. 12.18 | Class diagram modeling the generalization (i.e., inheritance)relationship between the base class Transaction and its derived classes

BalanceInquiry, Withdrawal and Deposit.

Page 70: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

70

12.8 Incorporating Inheritance and Polymorphism into the ATM System (Cont )Polymorphism into the ATM System (Cont.)

• Include operation Execute in base class Transaction so that the ATM can invoke each derived class’s overridden version.

• Figure 12.19 presents an updated class diagram.

2009 Pearson Education, Inc. All rights reserved.

Page 71: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

71

12.8 Incorporating Inheritance and Polymorphism into the ATM System (Cont )Polymorphism into the ATM System (Cont.)

2009 Pearson Education, Inc. All rights reserved.

Fig. 12.19 | Class diagram of the ATM system (incorporating inheritance).Note that MustInherit class name Transaction appears in italics.

Page 72: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

72

12.8 Incorporating Inheritance and Polymorphism into the ATM System (Cont )Polymorphism into the ATM System (Cont.)

Software Engineering Observation 12.6A complete class diagram shows all the associationsA complete class diagram shows all the associations among classes, and all the attributes and operations for each class. When the number of class attributes, operations and associations is substantial, a good practice that promotes readability is to divide this information between two class diagrams—one focusinginformation between two class diagrams—one focusing on associations and the other on attributes and operations.

2009 Pearson Education, Inc. All rights reserved.

Page 73: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

73

12.8 Incorporating Inheritance and Polymorphism into the ATM System (Cont )Polymorphism into the ATM System (Cont.)

2009 Pearson Education, Inc. All rights reserved.

Fig. 12.20| Class diagram after incorporating inheritance into the system.

Page 74: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

74

1.Transaction is a generalization of class

Outline

1 ' Class Withdrawal represents an ATM withdrawal transaction.

2 Public Class Withdrawal

1.Transaction is a generalization of classWithdrawal (Fig. 12.21).

2 Public Class Withdrawal

3 Inherits Transaction

4 5 End Class ' Withdrawal

i hd lFig. 12.21 | Visual Basic code for shell of class Withdrawal.

2009 Pearson Education, Inc. All rights reserved.

Page 75: VB 2008 HTP 12 [Read-Only]personal.kent.edu/~asamba/tech46330/Chap12.pdf · • Suppose we design a video game with objects of many types inheriting from classtypes, inheriting from

75

2.Withdrawal must implement the abstract operations

Outline

1 ' Class Withdrawal represents an ATM withdrawal transaction.

2 Public Class Withdrawal

2.Withdrawal must implement the abstract operationsof its base class (Fig. 12.22).

3 Inherits Transaction

4 5 ' attributes

6 Private amount As Decimal ' amount to withdraw

7 Private keypad As Keypad ' reference to keypad 7 Private keypad As Keypad reference to keypad

8 Private cashDispenser As CashDispenser ' reference to cash dispenser

9 10 ' parameterless constructor 11 Public Sub New() 12 ' constructor body code 13 End Sub ' New 14 15 ' method that overrides Execute 16 Public Overrides Sub Execute() 17 ' Execute method body code 18 End Sub ' Execute 19 End Class ' Withdrawal

Fi 12 22 | Vi l B i d f l Withd l b d

2009 Pearson Education, Inc. All rights reserved.

Fig. 12.22 | Visual Basic code for class Withdrawal based onFig. 12.19 and Fig. 12.20.