2009 pearson education, inc. all rights reserved. 1 12 polymorphism, interfaces operator...

96
1 2009 Pearson Education, Inc. All rights rese 1 2 Polymorphism, Interfaces & Operator Overloading

Upload: theodore-glenn

Post on 18-Jan-2018

229 views

Category:

Documents


0 download

DESCRIPTION

 2009 Pearson Education, Inc. All rights reserved. 3 A philosopher of imposing stature doesn’t think in a vacuum. Even his most abstract ideas are, to some extent, conditioned by what is or is not known in the time when he lives. – Alfred North Whitehead Why art thou cast down, O my soul? – Psalms 42:5

TRANSCRIPT

Page 1: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

1

2009 Pearson Education, Inc. All rights reserved.

12

Polymorphism, Interfaces & Operator

Overloading

Page 2: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

2

2009 Pearson Education, Inc. All rights reserved.

One Ring to rule them all, One Ring to find them,One Ring to bring them alland in the darkness bind them.

– John Ronald Reuel Tolkien

General propositions do notdecide concrete cases.

– Oliver Wendell Holmes

Page 3: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

3

2009 Pearson Education, Inc. All rights reserved.

A philosopher of imposing stature doesn’t thinkin a vacuum. Even his most abstract ideas are, to some extent, conditioned by what is or is notknown in the time when he lives.

– Alfred North Whitehead

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

Page 4: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

4

2009 Pearson Education, Inc. All rights reserved.

OBJECTIVESIn this chapter you will learn: The concept of polymorphism and how it

enables you to “program in the general.” To use overridden methods to effect

polymorphism. To distinguish between abstract and concrete

classes. To declare abstract methods to create abstract

classes.

Page 5: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

5

2009 Pearson Education, Inc. All rights reserved.

OBJECTIVES How polymorphism makes systems extensible

and maintainable. To determine an object’s type at execution time. To create sealed methods and classes. To declare and implement interfaces. To overload operators to enable them to

manipulate objects.

Page 6: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

6

2009 Pearson Education, Inc. All rights reserved.

12.1   Introduction12.2   Polymorphism Examples12.3   Demonstrating Polymorphic Behavior12.4   Abstract Classes and Methods12.5   Case Study: Payroll System Using Polymorphism12.6   sealed Methods and Classes12.7   Case Study: Creating and Using Interfaces12.8   Operator Overloading12.9   (Optional) Software Engineering Case Study:

Incorporating Inheritance and Polymorphisminto the ATM System

Page 7: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

7

2009 Pearson Education, Inc. All rights reserved.

12.1  Introduction

• Polymorphism enables you to write applications that process objects that share the same base class in a class hierarchy as if they were all objects of the base class.

• Polymorphism can improve extensibility.

Page 8: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

8

2009 Pearson Education, Inc. All rights reserved.

12.2  Polymorphism Examples

• If class Rectangle is derived from class Quadrilateral, then a Rectangle is a more specific version of a Quadrilateral.

• Any operation that can be performed on a Quadrilateral object can also be performed on a Rectangle object.

• These operations also can be performed on other Quadrilaterals, such as Squares, Parallelograms and Trapezoids.

• The polymorphism occurs when an application invokes a method through a base-class variable.

Page 9: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

9

2009 Pearson Education, Inc. All rights reserved.

12.2  Polymorphism Examples (Cont.)

• As another example, suppose we design a video game that manipulates objects of many different types, including objects of classes Martian, Venusian, Plutonian, SpaceShip and LaserBeam.

• Each class inherits from the common base class SpaceObject, which contains method Draw.

• A screen-manager application maintains a collection(e.g., a SpaceObject array) of references to objectsof the various classes.

• To refresh the screen, the screen manager periodically sends each object the same message—namely, Draw, while object responds in a unique way.

Page 10: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

10

2009 Pearson Education, Inc. All rights reserved.

12.2  Polymorphism Examples (Cont.)

Software Engineering Observation 12.1Polymorphism promotes extensibility: Software that invokes polymorphic behavior is independent of the object types to which messages are sent. Only client code that instantiates new objects must be modified to accommodate new types.

Page 11: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

11

2009 Pearson Education, Inc. All rights reserved.

12.3  Demonstrating Polymorphic Behavior

• In a method call on an object, the type of the actual referenced object, not the type of the reference, determines which method is called.

• An object of a derived class can be treated as an object of its base class.

• A base-class object is not an object of any of its derived classes.

• The is-a relationship applies from a derived class to its direct and indirect base classes, but not vice versa.

Page 12: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

12

2009 Pearson Education, Inc. All rights reserved.

12.3  Demonstrating Polymorphic Behavior (Cont.)

• The compiler allows the assignment of a base-class reference to a derived-class variable if we explicitly cast the base-class reference to the derived-class type

• If an application needs to perform a derived-class-specific operation on a derived-class object referenced by a base-class variable, the base-class reference must be downcasted to a derived-class reference

Page 13: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

13

2009 Pearson Education, Inc. All rights reserved.

1 // Fig. 12.1: PolymorphismTest.cs 2 // Assigning base-class and derived-class references to base-class and 3 // derived-class variables. 4 using System; 5 6 public class PolymorphismTest 7 { 8 public static void Main( string[] args ) 9 { 10 // assign base-class reference to base-class variable 11 CommissionEmployee3 commissionEmployee = new CommissionEmployee3( 12 "Sue", "Jones", "222-22-2222", 10000.00M, .06M ); 13 14 // assign derived-class reference to derived-class variable 15 BasePlusCommissionEmployee4 basePlusCommissionEmployee = 16 new BasePlusCommissionEmployee4( "Bob", "Lewis", 17 "333-33-3333", 5000.00M, .04M, 300.00M ); 18 19 // invoke ToString and Earnings on base-class object

Outline

• The example in Fig. 12.1 demonstrates three waysto use base-class and derived-class variables.

Fig. 12.1 | Assigning base-class and derived-class referencesto base-class and derived-class variables. (Part 1 of 3.)

PolymorphismTest.cs

(1 of 3 )

Create a new CommissionEmployee3 object and assign its reference to a CommissionEmployee3 variable.

Page 14: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

14

2009 Pearson Education, Inc. All rights reserved.

20 // using base-class variable 21 Console.WriteLine( "{0} {1}:\n\n{2}\n{3}: {4:C}\n", 22 "Call CommissionEmployee3's ToString with base-class reference", 23 "to base class object", commissionEmployee.ToString(), 24 "earnings", commissionEmployee.Earnings() ); 25 26 // invoke ToString and Earnings on derived-class object 27 // using derived-class variable 28 Console.WriteLine( "{0} {1}:\n\n{2}\n{3}: {4:C}\n", 29 "Call BasePlusCommissionEmployee4's ToString with derived class", 30 "reference to derived-class object", 31 basePlusCommissionEmployee.ToString(), 32 "earnings", basePlusCommissionEmployee.Earnings() ); 33 34 // invoke ToString and Earnings on derived-class object 35 // using base-class variable 36 CommissionEmployee3 commissionEmployee2 = 37 basePlusCommissionEmployee; 38 Console.WriteLine( "{0} {1}:\n\n{2}\n{3}: {4:C}", 39 "Call BasePlusCommissionEmployee4's ToString with base class", 40 "reference to derived-class object", 41 commissionEmployee2.ToString(), "earnings", 42 commissionEmployee2.Earnings() ); 43 } // end Main 44 } // end class PolymorphismTest

Outline

Fig. 12.1 | Assigning base-class and derived-class referencesto base-class and derived-class variables. (Part 2 of 3.)

PolymorphismTest.cs

(2 of 3 ) Use the reference commissionEmployee to invoke methods ToString and Earnings. Because commissionEmployee refers to a CommissionEmployee3 object, base class Commission­Employee3’s version of the methods are called.

Assign the reference to derived-class object basePlusCommissionEmployee to a base-class Commission­Employee3 variable.

Invoke methods ToString and Earnings on the base-class CommisionEmployee3, but the overriding derived-class’s (BasePlusCommissionEmployee4’s) version of the methods are actually called.

Page 15: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

15

2009 Pearson Education, Inc. All rights reserved.

Call CommissionEmployee3'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 commission rate: 0.06 earnings: $600.00 Call BasePlusCommissionEmployee4's ToString with derived-class reference to derived-class object: base-salaried commission employee: Bob Lewis social security number: 333-33-3333 gross sales: $5,000.00 commission rate: 0.04 base salary: $300.00 earnings: $500.00 Call BasePlusCommissionEmployee4's ToString with base-class reference to derived-class object: base-salaried commission employee: Bob Lewis social security number: 333-33-3333 gross sales: $5,000.00 commission rate: 0.04 base salary: $300.00 earnings: $500.00

Outline

Fig. 12.1 | Assigning base-class and derived-class referencesto base-class and derived-class variables. (Part 3 of 3.)

PolymorphismTest.cs

(3 of 3 )

Page 16: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

16

2009 Pearson Education, Inc. All rights reserved.

12.3  Demonstrating Polymorphic Behavior (Cont.)

• When the compiler encounters a method call made through a variable, it determines if the method can be called by checking the variable’s class type.

• At execution time, the type of the object to which the variable refers determines the actual method to use.

Page 17: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

17

2009 Pearson Education, Inc. All rights reserved.

12.4  Abstract Classes and Methods

• Abstract classes, or abstract base classes cannot be used to instantiate objects.

• Abstract base classes are too general to create real objects—they specify only what is common among derived classes.

• Classes that can be used to instantiate objects are called concrete classes.

• Concrete classes provide the specifics that make it reasonable to instantiate objects.

Page 18: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

18

2009 Pearson Education, Inc. All rights reserved.

• An abstract class normally contains one or more abstract methods, which have the keyword abstract in their declaration.

• A class that contains abstract methods must be declared as an abstract class even if it contains concrete (nonabstract) methods.

• Abstract methods do not provide implementations.

12.4  Abstract Classes and Methods (Cont.)

Page 19: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

19

2009 Pearson Education, Inc. All rights reserved.

12.4  Abstract Classes and Methods (Cont.)

• abstract property declarations have the form:public­abstract­PropertyType MyProperty{­get;­set;

}­//­end­abstract­property• An abstract property may omit implementations for the get

accessor, the set accessor or both.• Concrete derived classes must provide implementations for

every accessor declared in the abstract property.

Page 20: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

20

2009 Pearson Education, Inc. All rights reserved.

12.4  Abstract Classes and Methods (Cont.)

• Constructors and static methods cannot be declared abstract.

Software Engineering Observation 12.2An abstract class declares common attributes and behaviors of the various classes that inherit from it, either directly or indirectly, in a class hierarchy. An abstract class typically contains one or more abstract methods or properties that concrete derived classesmust override.

Page 21: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

21

2009 Pearson Education, Inc. All rights reserved.

Common Programming Error 12.1Attempting to instantiate an object of an abstractclass is a compilation error.

12.4  Abstract Classes and Methods (Cont.)

Common Programming Error 12.2Failure to implement a base class’s abstract methods and properties in a derived class is a compilation error unless the derived class is also declared abstract.

Page 22: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

22

2009 Pearson Education, Inc. All rights reserved.

12.4  Abstract Classes and Methods (Cont.)

• We can use abstract base classes to declare variables that can hold references to objects of any concrete classes derived from those abstract classes.

• You can use such variables to manipulate derived-class objects polymorphically and to invoke static methods declared in those abstract base classes.

• It is common in object-oriented programming to declare an iterator class that can traverse all the objects in a collection.

Page 23: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

23

2009 Pearson Education, Inc. All rights reserved.

12.5  Case Study: Payroll System Using Polymorphism

• In this section, we create an enhanced employee hierarchy to solve the following problem:A company pays its employees on a weekly basis. The employees are of four types: Salaried employees are paid a fixed weekly salary regardless of the number of hours worked, hourly employees are paid by the hour and receive overtime pay for all hours worked in excess of 40 hours, commission employees are paid a percentage of their sales, and salaried-commission employees receive a base salary plus a percentage of their sales. For the current pay period, the company has decided to reward salaried-commission employees by adding 10% to their base salaries.

Page 24: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

24

2009 Pearson Education, Inc. All rights reserved.

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

• We use abstract class Employee to represent the general concept of an employee.

• SalariedEmployee, CommissionEmployee and HourlyEmployee extend Employee.

• Class BasePlusCommissionEmployee—which extends CommissionEmployee—represents the last employee type.

Page 25: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

25

2009 Pearson Education, Inc. All rights reserved.

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

• The UML class diagram in Fig. 12.2 shows the inheritance hierarchy for our polymorphic employee payroll application.

Fig. 12.2 | Employee hierarchy UML class diagram

Page 26: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

26

2009 Pearson Education, Inc. All rights reserved.

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

Software Engineering Observation 12.3A derived class can inherit “interface” or “implementation” from a base class. Hierarchies designed for implementation inheritance tend to have their functionality high in the hierarchy. Hierarchies designed for interface inheritance tend to have their functionality lower in the hierarchy.

Page 27: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

27

2009 Pearson Education, Inc. All rights reserved.

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

• Class Employee provides methods Earnings and ToString, in addition to the properties that manipulate Employee’s instance variables.

• Each earnings calculation depends on the employee’s class,so we declare Earnings as abstract.

• The application iterates through the array and calls method Earnings for each Employee object. C# processes these method calls polymorphically.

• Each derived class overrides method ToString to create a string representation of an object of that class.

12.5.1 Creating Abstract Base Class Employee

Page 28: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

28

2009 Pearson Education, Inc. All rights reserved.

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

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

• The diagram in Fig. 12.3 shows each of the five classes in the hierarchy down the left side and methods Earnings and ToString across the top.

Page 29: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

29

2009 Pearson Education, Inc. All rights reserved.

1 // Fig. 12.4: Employee.cs 2 // Employee abstract base class. 3 public abstract class Employee 4 { 5 // read-only property that gets employee's first name 6 public string FirstName { get; private set; } 7 8 // read-only property that gets employee's last name 9 public string LastName { get; private set; } 10 11 // read-only property that gets employee's social security number 12 public string SocialSecurityNumber { get; private set; } 13 14 // three-parameter constructor 15 public Employee( string first, string last, string ssn ) 16 { 17 FirstName = first; 18 LastName = last; 19 SocialSecurityNumber = ssn; 20 } // end three-parameter Employee constructor

Outline

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

• The Employee class’s declaration is shown in Fig. 12.4.

Employee.cs

(1 of 2 )

Page 30: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

30

2009 Pearson Education, Inc. All rights reserved.

21 22 // return string representation of Employee object, using properties 23 public override string ToString() 24 { 25 return string.Format( "{0} {1}\nsocial security number: {2}", 26 FirstName, LastName, SocialSecurityNumber ); 27 } // end method ToString 28 29 // abstract method overridden by derived classes 30 public abstract decimal Earnings(); // no implementation here 31 } // end abstract class Employee

Outline

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

Employee.cs

(1 of 2 )

The Employee class includes an abstract method Earnings, which must be implemented by concrete derived classes.

Page 31: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

31

2009 Pearson Education, Inc. All rights reserved.

1 // Fig. 12.5: SalariedEmployee.cs 2 // SalariedEmployee class that extends Employee. 3 public class SalariedEmployee : Employee 4 { 5 private decimal weeklySalary; 6 7 // four-parameter constructor 8 public SalariedEmployee( string first, string last, string ssn, 9 decimal salary ) : base( first, last, ssn ) 10 { 11 WeeklySalary = salary; // validate salary via property 12 } // end four-parameter SalariedEmployee constructor 13 14 // property that gets and sets salaried employee's salary 15 public decimal WeeklySalary 16 { 17 get 18 { 19 return weeklySalary; 20 } // end get

Outline

Fig. 12.5 | SalariedEmployee class that extendsEmployee. (Part 1 of 2.)

SalariedEmployee.cs

(1 of 2 )

SalariedEmployee extends Employee.

Using the base class constructor to initialize the private variables not inherited from the base class.

Page 32: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

32

2009 Pearson Education, Inc. All rights reserved.

21 set 22 { 23 weeklySalary = ( ( value >= 0 ) ? value : 0 ); // validation 24 } // end set 25 } // end property WeeklySalary 26 27 // calculate earnings; override abstract method Earnings in Employee 28 public override decimal Earnings() 29 { 30 return WeeklySalary; 31 } // end method Earnings 32 33 // return string representation of SalariedEmployee object 34 public override string ToString() 35 { 36 return string.Format( "salaried employee: {0}\n{1}: {2:C}", 37 base.ToString(), "weekly salary", WeeklySalary ); 38 } // end method ToString 39 } // end class SalariedEmployee

Outline

Fig. 12.5 | SalariedEmployee class that extendsEmployee. (Part 2 of 2.)

SalariedEmployee.cs

(2 of 2 )

Method Earnings overrides Employee’s abstract method Earnings to provide a concrete implementation that returns the SalariedEmployee’s weekly salary.

Method ToString overrides Employee method ToString.

Page 33: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

33

2009 Pearson Education, Inc. All rights reserved.

1 // Fig. 12.6: HourlyEmployee.cs 2 // HourlyEmployee class that extends Employee. 3 public class HourlyEmployee : Employee 4 { 5 private decimal wage; // wage per hour 6 private decimal hours; // hours worked for the week 7 8 // five-parameter constructor 9 public HourlyEmployee( string first, string last, string ssn, 10 decimal hourlyWage, decimal hoursWorked ) 11 : base( first, last, ssn ) 12 { 13 Wage = hourlyWage; // validate hourly wage via property 14 Hours = hoursWorked; // validate hours worked via property 15 } // end five-parameter HourlyEmployee constructor 16 17 // property that gets and sets hourly employee's wage 18 public decimal Wage 19 { 20 get 21 { 22 return wage; 23 } // end get

Outline• Class HourlyEmployee (Fig. 12.6) also extends class Employee.

Fig. 12.6 | HourlyEmployee class that extendsEmployee. (Part 1 of 3.)

HourlyEmployee.cs

(1 of 3 )

Page 34: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

34

2009 Pearson Education, Inc. All rights reserved.

24 set 25 { 26 wage = ( value >= 0 ) ? value : 0; // validation 27 } // end set 28 } // end property Wage 29 30 // property that gets and sets hourly employee's hours 31 public decimal Hours 32 { 33 get 34 { 35 return hours; 36 } // end get 37 set 38 { 39 hours = ( ( value >= 0 ) && ( value <= 168 ) ) ? 40 value : 0; // validation 41 } // end set 42 } // end property Hours

Outline

Fig. 12.6 | HourlyEmployee class that extendsEmployee. (Part 2 of 3.)

HourlyEmployee.cs

(2 of 3 )

Method ToString overrides Employee method ToString.

The set accessor in property Hours ensures that hours is in the range 0–168 (the number of hours in a week).

Page 35: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

35

2009 Pearson Education, Inc. All rights reserved.

43 44 // calculate earnings; override Employee’s abstract method Earnings 45 public override decimal Earnings() 46 { 47 if ( Hours <= 40 ) // no overtime 48 return Wage * Hours; 49 else 50 return ( 40 * Wage ) + ( ( Hours - 40 ) * Wage * 1.5M ); 51 } // end method Earnings 52 53 // return string representation of HourlyEmployee object 54 public override string ToString() 55 { 56 return string.Format( 57 "hourly employee: {0}\n{1}: {2:C}; {3}: {4:F2}", 58 base.ToString(), "hourly wage", Wage, "hours worked", Hours ); 59 } // end method ToString 60 } // end class HourlyEmployee

Outline

Fig. 12.6 | HourlyEmployee class that extendsEmployee. (Part 3 of 3.)

HourlyEmployee.cs

(3 of 3 )

Page 36: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

36

2009 Pearson Education, Inc. All rights reserved.

1 // Fig. 12.7: CommissionEmployee.cs 2 // CommissionEmployee class that extends Employee. 3 public class CommissionEmployee : Employee 4 { 5 private decimal grossSales; // gross weekly sales 6 private decimal commissionRate; // commission percentage 7 8 // five-parameter constructor 9 public CommissionEmployee( string first, string last, string ssn, 10 decimal sales, decimal rate ) : base( first, last, ssn ) 11 { 12 GrossSales = sales; // validate gross sales via property 13 CommissionRate = rate; // validate commission rate via property 14 } // end five-parameter CommissionEmployee constructor 15 16 // property that gets and sets commission employee's commission rate 17 public decimal CommissionRate 18 { 19 get 20 { 21 return commissionRate; 22 } // end get

Outline• Class CommissionEmployee (Fig. 12.7) extends class Employee.

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

CommissionEmployee.cs

(1 of 3 )

Page 37: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

37

2009 Pearson Education, Inc. All rights reserved.

23 set 24 { 25 commissionRate = ( value > 0 && value < 1 ) ? 26 value : 0; // validation 27 } // end set 28 } // end property CommissionRate 29 30 // property that gets and sets commission employee's gross sales 31 public decimal GrossSales 32 { 33 get 34 { 35 return grossSales; 36 } // end get 37 set 38 { 39 grossSales = ( value >= 0 ) ? value : 0; // validation 40 } // end set 41 } // end property GrossSales

Outline

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

CommissionEmployee.cs

(2 of 3 )

Page 38: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

38

2009 Pearson Education, Inc. All rights reserved.

42 43 // calculate earnings; override abstract method Earnings in Employee 44 public override decimal Earnings() 45 { 46 return CommissionRate * GrossSales; 47 } // end method Earnings 48 49 // return string representation of CommissionEmployee object 50 public override string ToString() 51 { 52 return string.Format( "{0}: {1}\n{2}: {3:C}\n{4}: {5:F2}", 53 "commission employee", base.ToString(), 54 "gross sales", GrossSales, "commission rate", CommissionRate ); 55 } // end method ToString 56 } // end class CommissionEmployee

Outline

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

CommissionEmployee.cs

(3 of 3 )

Calling base-class method ToString to obtain the Employee-specific information.

Page 39: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

39

2009 Pearson Education, Inc. All rights reserved.

1 // Fig. 12.8: BasePlusCommissionEmployee.cs 2 // BasePlusCommissionEmployee class that extends CommissionEmployee. 3 public class BasePlusCommissionEmployee : CommissionEmployee 4 { 5 private decimal baseSalary; // base salary per week 6 7 // six-parameter constructor 8 public BasePlusCommissionEmployee( string first, string last, 9 string ssn, decimal sales, decimal rate, decimal salary ) 10 : base( first, last, ssn, sales, rate ) 11 { 12 BaseSalary = salary; // validate base salary via property 13 } // end six-parameter BasePlusCommissionEmployee constructor 14 15 // property that gets and sets 16 // base-salaried commission employee's base salary 17 public decimal BaseSalary 18 { 19 get 20 { 21 return baseSalary; 22 } // end get

Outline• Class BasePlusCommissionEmployee (Fig. 12.8) extends class Commission­Employee and therefore is an indirect derived class of class Employee.

Fig. 12.8 | BasePlusCommissionEmployee class that extends CommissionEmployee. (Part 1 of 2.)

BasePlusCommissionEmployee.cs

(1 of 2 )

Page 40: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

40

2009 Pearson Education, Inc. All rights reserved.

23 set 24 { 25 baseSalary = ( value >= 0 ) ? value : 0; // validation 26 } // end set 27 } // end property BaseSalary 28 29 // calculate earnings; override method Earnings in CommissionEmployee 30 public override decimal Earnings() 31 { 32 return BaseSalary + base.Earnings(); 33 } // end method Earnings 34 35 // return string representation of BasePlusCommissionEmployee object 36 public override string ToString() 37 { 38 return string.Format( "base-salaried {0}; base salary: {1:C}", 39 base.ToString(), BaseSalary ); 40 } // end method ToString 41 } // end class BasePlusCommissionEmployee

Outline

Fig. 12.8 | BasePlusCommissionEmployee class that extends CommissionEmployee. (Part 2 of 2.)

BasePlusCommissionEmployee.cs

(2 of 2 )

Method Earnings calls the base class’s Earnings method to calculate the commission-based portion of the employee’s earnings.

BasePlusCommissionEmployee’s ToString method creates a string that contains "base-salaried", followed by the string obtained by invoking base class CommissionEmployee’s ToString method (a good example of code reuse) then the base salary.

Page 41: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

41

2009 Pearson Education, Inc. All rights reserved.

1 // Fig. 12.9: PayrollSystemTest.cs 2 // Employee hierarchy test application. 3 using System; 4 5 public class PayrollSystemTest 6 { 7 public static void Main( string[] args ) 8 { 9 // create derived-class objects 10 SalariedEmployee salariedEmployee = 11 new SalariedEmployee( "John", "Smith", "111-11-1111", 800.00M ); 12 HourlyEmployee hourlyEmployee = 13 new HourlyEmployee( "Karen", "Price", 14 "222-22-2222", 16.75M, 40.0M ); 15 CommissionEmployee commissionEmployee = 16 new CommissionEmployee( "Sue", "Jones", 17 "333-33-3333", 10000.00M, .06M ); 18 BasePlusCommissionEmployee basePlusCommissionEmployee = 19 new BasePlusCommissionEmployee( "Bob", "Lewis", 20 "444-44-4444", 5000.00M, .04M, 300.00M ); 21

Outline• The application in Fig. 12.9 tests our Employee

hierarchy.

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

PayrollSystemTest.cs

(1 of 6 )

Create objects of each of the four concrete Employee derived classes.

Page 42: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

42

2009 Pearson Education, Inc. All rights reserved.

22 Console.WriteLine( "Employees processed individually:\n" ); 23 24 Console.WriteLine( "{0}\nearned: {1:C}\n", 25 salariedEmployee, salariedEmployee.Earnings() ); 26 Console.WriteLine( "{0}\nearned: {1:C}\n", 27 hourlyEmployee, hourlyEmployee.Earnings() ); 28 Console.WriteLine( "{0}\nearned: {1:C}\n", 29 commissionEmployee, commissionEmployee.Earnings() ); 30 Console.WriteLine( "{0}\nearned: {1:C}\n", 31 basePlusCommissionEmployee, 32 basePlusCommissionEmployee.Earnings() ); 33 34 // create four-element Employee array 35 Employee[] employees = new Employee[ 4 ]; 36 37 // initialize array with Employees of derived types 38 employees[ 0 ] = salariedEmployee; 39 employees[ 1 ] = hourlyEmployee; 40 employees[ 2 ] = commissionEmployee; 41 employees[ 3 ] = basePlusCommissionEmployee; 42

Outline

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

PayrollSystemTest.cs

(2 of 6 )

Each object’s ToString method is called implicitly.

Page 43: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

43

2009 Pearson Education, Inc. All rights reserved.

43 Console.WriteLine( "Employees processed polymorphically:\n" ); 44 45 // generically process each element in array employees 46 foreach ( var currentEmployee in employees ) 47 { 48 Console.WriteLine( currentEmployee ); // invokes ToString 49 50 // determine whether element is a BasePlusCommissionEmployee 51 if ( currentEmployee is BasePlusCommissionEmployee ) 52 { 53 // downcast Employee reference to 54 // BasePlusCommissionEmployee reference 55 BasePlusCommissionEmployee employee = 56 ( BasePlusCommissionEmployee ) currentEmployee; 57 58 employee.BaseSalary *= 1.10M; 59 Console.WriteLine( 60 "new base salary with 10% increase is: {0:C}", 61 employee.BaseSalary ); 62 } // end if

Outline

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

PayrollSystemTest.cs

(2 of 6 )

Method calls are resolved at execution time, based on the type of the object referenced by the variable.

The is operator is used to determine whether a particular Employee object’s type is BasePlusCommissionEmployee.

Downcasting current­Employee from type Employee to type BasePlusCommissionEmployee.

Page 44: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

44

2009 Pearson Education, Inc. All rights reserved.

63 64 Console.WriteLine( 65 "earned {0:C}\n", currentEmployee.Earnings() ); 66 } // end foreach 67 68 // get type name of each object in employees array 69 for ( int j = 0; j < employees.Length; j++ ) 70 Console.WriteLine( "Employee {0} is a {1}", j, 71 employees[ j ].GetType() ); 72 } // end Main 73 } // end class PayrollSystemTest Employees processed individually: salaried employee: John Smith social security number: 111-11-1111 weekly salary: $800.00 earned: $800.00 hourly employee: Karen Price social security number: 222-22-2222 hourly wage: $16.75; hours worked: 40.00 earned: $670.00 (continued on next page…)

Outline

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

PayrollSystemTest.cs

(3 of 6 )

Method calls are resolved at execution time, based on the type of the object referenced by the variable.

Method GetType returns an object of class Type, which contains information about the object’s type.

Page 45: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

45

2009 Pearson Education, Inc. All rights reserved.

(continued from previous page…) 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: $500.00 Employees processed polymorphically: salaried employee: John Smith social security number: 111-11-1111 weekly salary: $800.00 earned $800.00 (continued on previous page…)

Outline

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

PayrollSystemTest.cs

(5 of 6 )

Page 46: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

46

2009 Pearson Education, Inc. All rights reserved.

(continued from previous page…) weekly salary: $800.00 earned $800.00 hourly employee: Karen Price social security number: 222-22-2222 hourly wage: $16.75; hours worked: 40.00 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 new base salary with 10% increase is: $330.00 earned $530.00 Employee 0 is a SalariedEmployee Employee 1 is a HourlyEmployee Employee 2 is a CommissionEmployee Employee 3 is a BasePlusCommissionEmployee

Outline

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

PayrollSystemTest.cs

(6 of 6 )

Page 47: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

47

2009 Pearson Education, Inc. All rights reserved.

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

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

Software Engineering Observation 12.4If at execution time the reference to a derived-class object has been assigned to a variable of one of its direct or indirect base classes, it is acceptable to cast the reference stored in that base-class variable back to a reference of the derived-class type. Before performing such a cast, use the is operator to ensure that the object is indeed an object of an appropriate derived-class type.

Page 48: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

48

2009 Pearson Education, Inc. All rights reserved.

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

Common Programming Error 12.4When downcasting an object, an InvalidCastException (of namespace System) occurs if at execution time the object does not have an is-a relationship with the type specified in the cast operator. An object can be cast only to its own type or to the type of one of its base classes.

Page 49: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

49

2009 Pearson Education, Inc. All rights reserved.

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

• You can avoid a potential InvalidCastException by using the as operator to perform a downcast rather than a cast operator.

– If the downcast is invalid, the expression will be null instead of throwing an exception.

• Method GetType returns an object of class Type(of namespace System), which contains information aboutthe object’s type, including its class name, the names of its methods, and the name of its base class.

• The Type class’s ToString method returns the class name.

Page 50: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

50

2009 Pearson Education, Inc. All rights reserved.

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

12.5.7 Summary of the Allowed Assignments BetweenBase-Class and Derived-Class Variables• Assigning a base-class reference to a base-class variable is

straightforward.• Assigning a derived-class reference to a derived-class variable is

straightfor ward.• Assigning a derived-class reference to a base-class variable is safe,

because the derived-class object is an object of its base class. However, this reference can be used to refer only to base-class members.

• Attempting to assign a base-class reference to a derived-class variable is a compilation error. To avoid this error, the base-class reference must be cast to a derived-class type explicitly.

Page 51: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

51

2009 Pearson Education, Inc. All rights reserved.

12.6  sealed Methods and Classes

• A method declared sealed in a base class cannot be overridden in a derived class.

• Methods that are declared private are implicitly sealed.• Methods that are declared static also are implicitly sealed, because static methods cannot be overridden either.

• A derived-class method declared both override and sealed can override a base-class method, but cannot be overridden in classes further down the inheritance hierarchy.

• Calls to sealed methods are resolved at compile time—this is known as static binding.

Page 52: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

52

2009 Pearson Education, Inc. All rights reserved.

12.6  sealed Methods and Classes (Cont.)

Performance Tip 12.1The compiler can decide to inline a sealed method call and will do so for small, simple sealed methods. Inlining does not violate encapsulation or information hiding, but does improve performance, because it eliminates the overhead of making a method call.

Page 53: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

53

2009 Pearson Education, Inc. All rights reserved.

12.6  sealed Methods and Classes (Cont.)

• A class that is declared sealed cannot be a base class (i.e., a class cannot extend a sealed class).

• All methods in a sealed class are implicitly sealed.• Class string is a sealed class. This class cannot be

extended, so applications that use strings can rely on the functionality of string objects as specified in the Framework Class Library.

Page 54: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

54

2009 Pearson Education, Inc. All rights reserved.

12.6  sealed Methods and Classes (Cont.)

Common Programming Error 12.5Attempting to declare a derived class of a sealed class is a compilation error.

Software Engineering Observation 12.5In the Framework Class Library, the vast majority of classes are not declared sealed. This enables inheritance and polymorphism—the fundamental capabilities of object-oriented programming.

Page 55: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

55

2009 Pearson Education, Inc. All rights reserved.

12.7  Case Study: Creating and Using Interfaces

• Interfaces define and standardize the ways in which people and systems can interact with one another.

• A C# interface describes a set of methods that can be called on an object—to tell it, for example, to perform some task or return some piece of information.

• An interface declaration begins with the keyword interface and can contain only abstract methods, properties, indexers and events.

• All interface members are implicitly declared both public and abstract.

• An interface can extend one or more other interfaces to create a more elaborate interface that other classes can implement.

Page 56: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

56

2009 Pearson Education, Inc. All rights reserved.

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

Common Programming Error 12.6It is a compilation error to declare an interface member public or abstract explicitly, because they are redundant in interface-member declarations. It is also a compilation error to specify any implementation details, such as concrete method declarations, in an interface.

Page 57: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

57

2009 Pearson Education, Inc. All rights reserved.

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

• To use an interface, a class must specify that it implements the interface by listing the interface after the colon (:) in the class declaration.

• A concrete class implementing an interface must declare each member of the interface with the signature specified in the interface declaration.

• A class that implements an interface but does not implement all its members is an abstract class—it must be declared abstract and must contain an abstract declaration for each unimplemented member of the interface.

Common Programming Error 12.7Failing to declare any member of an interface in a class that implements the interface results in a compilation error.

Page 58: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

58

2009 Pearson Education, Inc. All rights reserved.

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

• An interface is typically used when disparate (i.e., unrelated) classes need to share common methods so that they can be processed polymorphically

• A programmer can create an interface that describes the desired functionality, then implement this interface in any classes requiring that functionality.

• An interface often is used in place of an abstract class when there is no default implementation to inherit—that is, no fields and no default method implementations.

• Like abstract classes, interfaces are typically public types, so they are normally declared in files by themselves with the same name as the interface and the .cs file-name extension.

Page 59: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

59

2009 Pearson Education, Inc. All rights reserved.

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

12.7.1 Developing an IPayable Hierarchy• To build an application that can determine payments for

employees and invoices alike, we first create an interface named IPayable.

• Interface IPayable contains method GetPaymentAmount that returns a decimal amount to be paid for an object of any class that implements the interface.

Page 60: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

60

2009 Pearson Education, Inc. All rights reserved.

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

Good Programming Practice 12.1By convention, the name of an interface begins with "I". This helps distinguish interfaces from classes, improvingcode readability.

Good Programming Practice 12.2When declaring a method in an interface, choose a name that describes the method’s purpose in a general manner, because the method may be implemented by a broad range of unrelated classes.

Page 61: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

61

2009 Pearson Education, Inc. All rights reserved.

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

• The UML class diagram in Fig. 12.10 shows the interface and class hierarchy used in our accounts-payable application.

Fig. 12.10 | IPayable interface and class hierarchy UML class diagram.

Page 62: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

62

2009 Pearson Education, Inc. All rights reserved.

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

• The UML distinguishes an interface from a class by placing the word “interface” in guillemets (« and ») above the interface name.

• The UML expresses the relationship between a class and an interface through a realization.

Page 63: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

63

2009 Pearson Education, Inc. All rights reserved.

1 // Fig. 12.11: IPayable.cs 2 // IPayable interface declaration. 3 public interface IPayable 4 { 5 decimal GetPaymentAmount(); // calculate payment; no implementation 6 } // end interface IPayable

Outline

Fig. 12.11 | IPayable interface declaration.

• Interface IPayable is declared in Fig. 12.11.IPayable.cs

Page 64: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

64

2009 Pearson Education, Inc. All rights reserved.

1 // Fig. 12.12: Invoice.cs 2 // Invoice class implements IPayable. 3 public class Invoice : IPayable 4 { 5 private int quantity; 6 private decimal pricePerItem; 7 8 // property that gets and sets the part number on the invoice 9 public string PartNumber { get; set; } 10 11 // property that gets and sets the part description on the invoice 12 public string PartDescription { get; set; } 13 14 // four-parameter constructor 15 public Invoice( string part, string description, int count, 16 decimal price ) 17 { 18 PartNumber = part; 19 PartDescription = description; 20 Quantity = count; // validate quantity via property 21 PricePerItem = price; // validate price per item via property 22 } // end four-parameter Invoice constructor

Outline

Invoice.cs

( 1 of 3 )

• We now create class Invoice (Fig. 12.12) represents a simple invoice that contains billing information for one kind of part.

Fig. 12.12 | Invoice class implements IPayable. (Part 1 of 3.)

Class Invoice implements interface IPayable. Like all classes, class Invoice also implicitly inherits from class object.

Page 65: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

65

2009 Pearson Education, Inc. All rights reserved.

23 24 // property that gets and sets the quantity on the invoice 25 public int Quantity 26 { 27 get 28 { 29 return quantity; 30 } // end get 31 set 32 { 33 quantity = ( value < 0 ) ? 0 : value; // validate quantity 34 } // end set 35 } // end property Quantity 36 37 // property that gets and sets the price per item 38 public decimal PricePerItem 39 { 40 get 41 { 42 return pricePerItem; 43 } // end get

Outline

Invoice.cs

( 2 of 3 )

Fig. 12.12 | Invoice class implements IPayable. (Part 2 of 3.)

Page 66: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

66

2009 Pearson Education, Inc. All rights reserved.

44 set 45 { 46 pricePerItem = ( value < 0 ) ? 0 : value; // validate price 47 } // end set 48 } // end property PricePerItem 49 50 // return string representation of Invoice object 51 public override string ToString() 52 { 53 return string.Format( 54 "{0}: \n{1}: {2} ({3}) \n{4}: {5} \n{6}: {7:C}", 55 "invoice", "part number", PartNumber, PartDescription, 56 "quantity", Quantity, "price per item", PricePerItem ); 57 } // end method ToString 58 59 // method required to carry out contract with interface IPayable 60 public decimal GetPaymentAmount() 61 { 62 return Quantity * PricePerItem; // calculate total cost 63 } // end method GetPaymentAmount 64 } // end class Invoice

Invoice implements the IPayable interface by declaring a GetPaymentAmount method.

Outline

Invoice.cs

( 3 of 3 )

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

Page 67: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

67

2009 Pearson Education, Inc. All rights reserved.

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

• C# does not allow derived classes to inherit from more than one base class, but it does allow a class to implement any number of interfaces.

• To implement more than one interface, use a comma-separated list of interface names after the colon (:) in the class declaration.

• When a class inherits from a base class and implements one or more interfaces, the class declaration must list the base-class name before any interface names.

Page 68: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

68

2009 Pearson Education, Inc. All rights reserved.

1 // Fig. 12.13: Employee.cs 2 // Employee abstract base class. 3 public abstract class Employee : IPayable 4 { 5 // read-only property that gets employee's first name 6 public string FirstName { get; private set; } 7 8 // read-only property that gets employee's last name 9 public string LastName { get; private set; } 10 11 // read-only property that gets employee's social security number 12 public string SocialSecurityNumber { get; private set; } 13 14 // three-parameter constructor 15 public Employee( string first, string last, string ssn ) 16 { 17 FirstName = first; 18 LastName = last; 19 SocialSecurityNumber = ssn; 20 } // end three-parameter Employee constructor

Outline

Employee.cs

( 1 of 2 )

• Figure 12.13 contains the Employee class, modified to implement interface IPayable.

Fig. 12.13 | Employee abstract base class. (Part 1 of 2.)

Class Employee now implements interface IPayable.

Page 69: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

69

2009 Pearson Education, Inc. All rights reserved.

21 22 // return string representation of Employee object 23 public override string ToString() 24 { 25 return string.Format( "{0} {1}\nsocial security number: {2}", 26 FirstName, LastName, SocialSecurityNumber ); 27 } // end method ToString 28 29 // Note: We do not implement IPayable method GetPaymentAmount here, so 30 // this class must be declared abstract to avoid a compilation error. 31 public abstract decimal GetPaymentAmount(); 32 } // end abstract class Employee

Outline

Employee.cs

( 2 of 2 )

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

Earnings has been renamed to GetPaymentAmount to match the interface’s requirements.

Page 70: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

70

2009 Pearson Education, Inc. All rights reserved.

1 // Fig. 12.14: SalariedEmployee.cs 2 // SalariedEmployee class that extends Employee. 3 public class SalariedEmployee : Employee 4 { 5 private decimal weeklySalary; 6 7 // four-parameter constructor 8 public SalariedEmployee( string first, string last, string ssn, 9 decimal salary ) : base( first, last, ssn ) 10 { 11 WeeklySalary = salary; // validate salary via property 12 } // end four-parameter SalariedEmployee constructor 13 14 // property that gets and sets salaried employee's salary 15 public decimal WeeklySalary 16 { 17 get 18 { 19 return weeklySalary; 20 } // end get

Outline

SalariedEmployee.cs

( 1 of 2 )

• Figure 12.14 contains a modified version of class SalariedEmployee that extends Employee and implements method GetPaymentAmount.

Fig. 12.14 | SalariedEmployee class that extendsEmployee. (Part 1 of 2.)

Page 71: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

71

2009 Pearson Education, Inc. All rights reserved.

21 set 22 { 23 weeklySalary = value < 0 ? 0 : value; // validation 24 } // end set 25 } // end property WeeklySalary 26 27 // calculate earnings; implement interface IPayable method 28 // that was abstract in base class Employee 29 public override decimal GetPaymentAmount() 30 { 31 return WeeklySalary; 32 } // end method GetPaymentAmount 33 34 // return string representation of SalariedEmployee object 35 public override string ToString() 36 { 37 return string.Format( "salaried employee: {0}\n{1}: {2:C}", 38 base.ToString(), "weekly salary", WeeklySalary ); 39 } // end method ToString 40 } // end class SalariedEmployee

Outline

SalariedEmployee.cs

( 2 of 2 )

Fig. 12.14 | SalariedEmployee class that extendsEmployee. (Part 2 of 2.)

Method GetPaymentAmount replaces method Earnings, keeping the same functionality.

Page 72: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

72

2009 Pearson Education, Inc. All rights reserved.

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

• The remaining Employee derived classes also must be modified to contain method GetPaymentAmount in place of Earnings to reflect the fact that Employee now implements IPayable.

• When a class implements an interface, the same is-a relationship provided by inheritance applies.

Page 73: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

73

2009 Pearson Education, Inc. All rights reserved.

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

Software Engineering Observation 12.6Inheritance and interfaces are similar in their implementation of the is-a relationship. An object of a class that implements an interface may be thought of as an object of that interface type.

Software Engineering Observation 12.7The is-a relationship that exists between base classes and derived classes, and between interfaces and the classes that implement them, holds when passing an object to a method.

Page 74: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

74

2009 Pearson Education, Inc. All rights reserved.

1 // Fig. 12.15: PayableInterfaceTest.cs 2 // Tests interface IPayable with disparate classes. 3 using System; 4 5 public class PayableInterfaceTest 6 { 7 public static void Main( string[] args ) 8 { 9 // create four-element IPayable array 10 IPayable[] payableObjects = new IPayable[ 4 ]; 11 12 // populate array with objects that implement IPayable 13 payableObjects[ 0 ] = new Invoice( "01234", "seat", 2, 375.00M ); 14 payableObjects[ 1 ] = new Invoice( "56789", "tire", 4, 79.95M ); 15 payableObjects[ 2 ] = new SalariedEmployee( "John", "Smith", 16 "111-11-1111", 800.00M ); 17 payableObjects[ 3 ] = new SalariedEmployee( "Lisa", "Barnes", 18 "888-88-8888", 1200.00M );

Outline

PayableInterfaceTest.cs

( 1 of 3 )

• PayableInterfaceTest (Fig. 12.15) illustrates that interface IPayable can be used to processes a set of Invoices and Employees polymorphically in a single application.

Fig. 12.15 | Tests interface IPayable with disparateclasses. (Part 1 of 3.)

Page 75: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

75

2009 Pearson Education, Inc. All rights reserved.

19 20 Console.WriteLine( 21 "Invoices and Employees processed polymorphically:\n" ); 22 23 // generically process each element in array payableObjects 24 foreach ( var currentPayable in payableObjects ) 25 { 26 // output currentPayable and its appropriate payment amount 27 Console.WriteLine( "payment due \n{0}: {1:C}\n", 28 currentPayable, currentPayable.GetPaymentAmount() ); 29 } // end foreach 30 } // end Main 31 } // end class PayableInterfaceTest Invoices and Employees processed polymorphically: invoice: part number: 01234 (seat) quantity: 2 price per item: $375.00 payment due: $750.00 (continued on next page...)

Outline

PayableInterfaceTest.cs

( 2 of 3 )

Fig. 12.15 | Tests interface IPayable with disparateclasses. (Part 2 of 3.)

Page 76: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

76

2009 Pearson Education, Inc. All rights reserved.

(continued from previous page…) invoice: part number: 56789 (tire) quantity: 4 price per item: $79.95 payment due: $319.80 salaried employee: John Smith social security number: 111-11-1111 weekly salary: $800.00 payment due: $800.00 salaried employee: Lisa Barnes social security number: 888-88-8888 weekly salary: $1,200.00 payment due: $1,200.00

Outline

PayableInterfaceTest.cs

( 3 of 3 )

Fig. 12.15 | Tests interface IPayable with disparateclasses. (Part 3 of 3.)

Software Engineering Observation 12.8All methods of class object can be called by using a referenceof an interface type—the reference refers to an object, and allobjects inherit the methods of class object.

Page 77: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

77

2009 Pearson Education, Inc. All rights reserved.

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

• 12.7.7 Common Interfaces of the .NET Framework Class Library

Interface Description

­ IComparable Objects of a class that implements the interface can be compared to one another.

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

­ IDisposable Implemented by classes that must provide an explicit mechanism for releasing resources.

­ IEnumerator Used for iterating through the elements of a collection (such as an array) one element at a time.

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

Page 78: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

78

2009 Pearson Education, Inc. All rights reserved.

Software Engineering Observation 12.9Use operator overloading when it makes anapplication clearer than accomplishing the sameoperations with explicit method calls.

Outline

ComplexNumber.cs

( 1 of 4 )

• C# enables you to overload most operators to make them sensitive to the context in which they are used.

• Class ComplexNumber (Fig. 12.17) overloads the plus (+), minus (-) and multiplication (*) operators to enable programs to add, subtract and multiply instances of class ComplexNumber using common mathematical notation.

Page 79: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

79

2009 Pearson Education, Inc. All rights reserved.

1 // Fig. 12.17: ComplexNumber.cs 2 // Class that overloads operators for adding, subtracting 3 // and multiplying complex numbers. 4 using System; 5 6 public class ComplexNumber 7 { 8 // read-only property that gets the real component 9 public double Real { get; private set; } 10 11 // read-only property that gets the imaginary component 12 public double Imaginary { get; private set; } 13 14 // constructor 15 public ComplexNumber( double a, double b ) 16 { 17 Real = a; 18 Imaginary = b; 19 } // end constructor

Outline

ComplexNumber.cs

( 2 of 4 )

Fig. 12.17 | Class that overloads operators for adding, subtractingand multiplying complex numbers. (Part 1 of 3.)

Page 80: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

80

2009 Pearson Education, Inc. All rights reserved.

20 21 // return string representation of ComplexNumber 22 public override string ToString() 23 { 24 return string.Format( "({0} {1} {2}i)", 25 Real, ( Imaginary < 0 ? "-" : "+" ), Math.Abs( Imaginary ) ); 26 } // end method ToString 27 28 // overload the addition operator 29 public static ComplexNumber operator +( 30 ComplexNumber x, ComplexNumber y ) 31 { 32 return new ComplexNumber( x.Real + y.Real, 33 x.Imaginary + y.Imaginary ); 34 } // end operator + 35

Outline

ComplexNumber.cs

( 3 of 4 )

Fig. 12.17 | Class that overloads operators for adding, subtractingand multiplying complex numbers. (Part 2 of 3.)

Overload the plus operator (+) to perform addition of ComplexNumbers

Page 81: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

81

2009 Pearson Education, Inc. All rights reserved.

36 // overload the subtraction operator 37 public static ComplexNumber operator -( 38 ComplexNumber x, ComplexNumber y ) 39 { 40 return new ComplexNumber( x.Real - y.Real, 41 x.Imaginary - y.Imaginary ); 42 } // end operator - 43 44 // overload the multiplication operator 45 public static ComplexNumber operator *( 46 ComplexNumber x, ComplexNumber y ) 47 { 48 return new ComplexNumber( 49 x.Real * y.Real - x.Imaginary * y.Imaginary, 50 x.Real * y.Imaginary + y.Real * x.Imaginary ); 51 } // end operator * 52 } // end class ComplexNumber

Outline

ComplexNumber.cs

( 4 of 4 )

Fig. 12.17 | Class that overloads operators for adding, subtractingand multiplying complex numbers. (Part 3 of 3.)

Page 82: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

82

2009 Pearson Education, Inc. All rights reserved.

12.8  Operator Overloading (Cont.)

• Keyword operator, followed by an operator symbol, indicates that a method overloads the specified operator.

• Methods that overload binary operators must take two arguments—the first argument is the left operand, and the second argument is the right operand.

• Overloaded operator methods must be public and static.

Page 83: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

83

2009 Pearson Education, Inc. All rights reserved.

12.8  Operator Overloading (Cont.)

Software Engineering Observation 12.10Overload operators to perform the same function or similar functions on class objects as the operators perform on objects of simple types. Avoid nonintuitive use of operators.

Software Engineering Observation 12.11At least one argument of an overloaded operator method must be a reference to an object of the class in which the operator is overloaded. This prevents programmers from changing how operators work on simple types.

Page 84: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

84

2009 Pearson Education, Inc. All rights reserved.

1 // Fig. 12.18: OperatorOverloading.cs 2 // Overloading operators for complex numbers. 3 using System; 4 5 public class ComplexTest 6 { 7 public static void Main( string[] args ) 8 { 9 // declare two variables to store complex numbers 10 // to be entered by user 11 ComplexNumber x, y; 12 13 // prompt the user to enter the first complex number 14 Console.Write( "Enter the real part of complex number x: " ); 15 double realPart = Convert.ToDouble( Console.ReadLine() ); 16 Console.Write( 17 "Enter the imaginary part of complex number x: " ); 18 double imaginaryPart = Convert.ToDouble( Console.ReadLine() ); 19 x = new ComplexNumber( realPart, imaginaryPart ); 20

Outline

OperatorOverloading.cs

( 1 of 2 )

• Class ComplexTest (Fig. 12.18) demonstrates the overloaded operators for adding, subtracting and multiplying ComplexNumbers.

Fig. 12.18 | Overloading operators for complexnumbers. (Part 1 of 2.)

Page 85: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

85

2009 Pearson Education, Inc. All rights reserved.

21 // prompt the user to enter the second complex number 22 Console.Write( "\nEnter the real part of complex number y: " ); 23 realPart = Convert.ToDouble( Console.ReadLine() ); 24 Console.Write( 25 "Enter the imaginary part of complex number y: " ); 26 imaginaryPart = Convert.ToDouble( Console.ReadLine() ); 27 y = new ComplexNumber( realPart, imaginaryPart ); 28 29 // display the results of calculations with x and y 30 Console.WriteLine(); 31 Console.WriteLine( "{0} + {1} = {2}", x, y, x + y ); 32 Console.WriteLine( "{0} - {1} = {2}", x, y, x - y ); 33 Console.WriteLine( "{0} * {1} = {2}", x, y, x * y ); 34 } // end method Main 35 } // end class ComplexTest Enter the real part of complex number x: 2 Enter the imaginary part of complex number x: 4 Enter the real part of complex number y: 4 Enter the imaginary part of complex number y: -2 (2 + 4i) + (4 - 2i) = (6 + 2i) (2 + 4i) - (4 - 2i) = (-2 + 6i) (2 + 4i) * (4 - 2i) = (16 + 12i)

Outline

OperatorOverloading.cs

(2 of 2 )

Fig. 12.18 | Overloading operators for complexnumbers. (Part 2 of 2.)

Add, subtract and multiply x and y with the overloaded operators, then output the results.

Page 86: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

86

2009 Pearson Education, Inc. All rights reserved.

12.9 (Optional) Software Engineering Case Study: Incorporating Inheritance and Polymorphism into the ATM System

• The UML specifies a relationship called a generalization to model inheritance.

• Figure 12.20 is the class diagram that models the inheritance relationship between base class Transaction and its three derived classes.

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

Page 87: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

87

2009 Pearson Education, Inc. All rights reserved.

12.9 (Optional) Software Engineering Case Study: Incorporating Inheritance and Polymorphism into the ATM System (Cont.)

• The arrows with triangular hollow arrowheads indicate that classes BalanceInquiry, Withdrawal and Deposit are derived from class Transaction by inheritance.

– Class Transaction is said to be a generalization of its derived classes.

– The derived classes are said to be specializations of class Transaction.

Page 88: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

88

2009 Pearson Education, Inc. All rights reserved.

12.9 (Optional) Software Engineering Case Study: Incorporating Inheritance and Polymorphism into the ATM System (Cont.)

• As Fig. 12.19 shows, classes BalanceInquiry, Withdrawal and Deposit share private int attribute accountNumber.

• Because the derived classes in this case do not need to modify attribute accountNumber, we have chosen to replace private attribute accountNumber in our model with the publicread-only property AccountNumber.

• Since this is a read-only property, it provides only a get accessor to access the account number.

• We declare Execute as an abstract operation in base class Transaction—it will become an abstract method in the C# implementation.

Page 89: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

89

2009 Pearson Education, Inc. All rights reserved.

12.9 (Optional) Software Engineering Case Study: Incorporating Inheritance and Polymorphism into the ATM System (Cont.)

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

derived classes BalanceInquiry, Withdrawal and Deposit.

Page 90: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

90

2009 Pearson Education, Inc. All rights reserved.

12.9 (Optional) Software Engineering Case Study: Incorporating Inheritance and Polymorphism into the ATM System (Cont.)

• Figure 12.21 presents an updated class diagram of our model that incorporates inheritance and introduces abstract base class Transaction.

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

Page 91: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

91

2009 Pearson Education, Inc. All rights reserved.

12.9 (Optional) Software Engineering Case Study: Incorporating Inheritance and Polymorphism into the ATM System (Cont.)

• We model an association between class ATM and class Transaction to show that the ATM, at any given moment, either is executing a transaction or is not.

• Because a Withdrawal is a type of Transaction, we no longer draw an association line directly between class ATM and class Withdrawal—derived class Withdrawal inherits base class Transaction’s association with class ATM.

• Derived classes BalanceInquiry and Deposit alsoinherit this association, which replaces the previously omitted associations between classes BalanceInquiry and Deposit, and class ATM.

Page 92: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

92

2009 Pearson Education, Inc. All rights reserved.

12.9 (Optional) Software Engineering Case Study: Incorporating Inheritance and Polymorphism into the ATM System (Cont.)

• We also add an association between Transaction and BankDatabase (Fig. 12.21). All Transactions require a reference to the BankDatabase so that they can access and modify account information.

• We include an association between class Transaction and the Screen because all Transactions display output to the user via the Screen.

• Class Withdrawal still participates in associations with the CashDispenser and the Keypad.

Page 93: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

93

2009 Pearson Education, Inc. All rights reserved.

12.9 (Optional) Software Engineering Case Study: Incorporating Inheritance and Polymorphism into the ATM System (Cont.)

• We present a modified class diagram in Fig. 12.22 that includes abstract base class Transaction.

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

Page 94: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

94

2009 Pearson Education, Inc. All rights reserved.

12.9 (Optional) Software Engineering Case Study: Incorporating Inheritance and Polymorphism into the ATM System (Cont.)

Software Engineering Observation 12.12A complete class diagram shows all the associations among classes, and all the attributes and operationsfor each class. When the number of class attributes, operations and associations is substantial, a good practice is to divide this information between two class diagrams—one focusing on associations and the otheron attributes and operations.

Page 95: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

95

2009 Pearson Education, Inc. All rights reserved.

1 // Fig. 12.23: Withdrawal.cs 2 // Class Withdrawal represents an ATM withdrawal transaction. 3 public class Withdrawal : Transaction 4 { 5 // code for members of class Withdrawal 6 } // end class Withdrawal

Outline

Withdrawal.cs

Implementing the ATM System Design Incorporating Inheritance• If a class A is a generalization of class B, then class B

is derived from (and is a specialization of) class A.• Figure 12.23 contains the shell of class Withdrawal,

in which the class definition indicates the inheritance relationship between Withdrawal and Transaction.

Fig. 12.23 | C# code for shell of class Withdrawal.

• If class A is an abstract class and class B is derived from class A, then class B must implement the abstract operations of class A if class B is to be a concrete class.

Page 96: 2009 Pearson Education, Inc. All rights reserved. 1 12 Polymorphism, Interfaces  Operator Overloading

96

2009 Pearson Education, Inc. All rights reserved.

1 // Fig. 12.24: Withdrawal.cs 2 // Class Withdrawal represents an ATM withdrawal transaction. 3 public class Withdrawal : Transaction 4 { 5 // attributes 6 private decimal amount; // amount to withdraw 7 private Keypad keypad; // reference to keypad 8 private CashDispenser cashDispenser; // reference to cash dispenser 9 10 // parameterless constructor 11 public Withdrawal() 12 { 13 // constructor body code 14 } // end constructor 15 16 // method that overrides Execute 17 public override void Execute() 18 { 19 // Execute method body code 20 } // end method Execute 21 } // end class Withdrawal

Outline

Withdrawal.cs

• Figure 12.24 contains the portions of the C# code for class Withdrawal.

Fig. 12.24 | C# code for class Withdrawal based onFigures 12.21 and 12.22.