Presentation is loading. Please wait.

Presentation is loading. Please wait.

Polymorphism, Interfaces & Operator Overloading

Similar presentations


Presentation on theme: "Polymorphism, Interfaces & Operator Overloading"— Presentation transcript:

1 Polymorphism, Interfaces & Operator Overloading
11 Polymorphism, Interfaces & Operator Overloading

2 General propositions do not decide concrete cases.
One Ring to rule them all, One Ring to find them, One Ring to bring them all and in the darkness bind them. John Ronald Reuel Tolkien General propositions do not decide concrete cases. Oliver Wendell Holmes

3 Why art thou cast down, O my soul?
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

4 OBJECTIVES In 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. 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.

5 11.1 Introduction 11.2 Polymorphism Examples 11.3 Demonstrating Polymorphic Behavior 11.4 Abstract Classes and Methods 11.5 Case Study: Payroll System Using Polymorphism Creating Abstract Base Class Employee Creating Concrete Derived Class SalariedEmployee Creating Concrete Derived Class HourlyEmployee Creating Concrete Derived Class CommissionEmployee Creating Indirect Concrete Derived Class BasePlusCommissionEmployee Polymorphic Processing, Operator is and Downcasting Summary of the Allowed Assignments Between Base Class and Derived Class Variables

6 11.6   sealed Methods and Classes
11.7   Case Study: Creating and Using Interfaces 11.7.1  Developing an IPayable Hierarchy 11.7.2  Declaring Interface IPayable 11.7.3  Creating Class Invoice 11.7.4  Modifying Class Employee to Implement Interface IPayable 11.7.5  Modifying Class SalariedEmployee for Use in the IPayable Hierarchy 11.7.6  Using Interface IPayable to Process Invoices and Employees Polymorphically 11.7.7  Common Interfaces of the .NET Framework Class Library 11.8   Operator Overloading 11.9   (Optional) Software Engineering Case Study: Incorporating Inheritance and Polymorphism into the ATM System 11.10   Wrap-Up

7 11.1 Introduction Polymorphism Interfaces
Enables “programming in the general” The same invocation can produce “many forms” of results Interfaces Implemented by classes to assign common functionality to possibly unrelated classes

8 11.2 Polymorphism Examples
When a program invokes a method through a base class variable, the correct derived class version of the method is called Based on the type of the reference stored in the base class variable The same method name and signature can cause different actions to occur Depends on the type of object on which the method is invoked Facilitates adding new classes to a system with minimal modifications to the system’s code

9 Software Engineering Observation 11.1
Polymorphism promotes extensibility: Software that invokes polymorphic behavior is independent 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 without requiring modification of the base system. Only client code that instantiates new objects must be modified to accommodate new types.

10 11.3 Demonstrating Polymorphic Behavior
Downcasting A base class reference can be aimed at a derived class object This is possible because a derived class object is a base class object as well When invoking a method from that reference, the type of the actual referenced object, not the type of the reference, determines which method is called Cannot treat a base class object as a derived class object

11 Outline PolymorphismTest .cs (1 of 3) Typical reference assignments

12 Outline PolymorphismTest .cs (2 of 3) Assign a reference to a BasePlusCommissionEmployee4 object to a CommissionEmployee3 variable Polymorphically call basePlusCommissionEmployee’s ToString method

13 Outline PolymorphismTest .cs (3 of 3)

14 11.4 Abstract Classes and Methods
Classes that are too general to create real objects Used only as abstract base classes for concrete derived classes and to declare reference variables Many inheritance hierarchies have abstract base classes occupying the top few levels Constructors and static methods cannot be abstract Keyword abstract Use to declare a class abstract Also use to declare a method abstract Abstract classes normally contain one or more abstract methods All concrete derived classes must override all inherited abstract methods

15 11.4 Abstract Classes and Methods (Cont.)
Iterator class Traverses all the objects in a collection, such as an array Often used in polymorphic programming to traverse a collection that contains references to objects from various levels of a hierarchy

16 Software Engineering Observation 11.2
An 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 classes must override. The instance variables, concrete methods and concrete properties of an abstract class are subject to the normal rules of inheritance.

17 Common Programming Error 11.1
Attempting to instantiate an object of an abstract class is a compilation error.

18 Common Programming Error 11.2
Failure 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.

19 Software Engineering Observation 11.3
A 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—each new derived class inherits one or more methods that were implemented in a base class, and the derived class uses the base class implementations. Hierarchies designed for interface inheritance tend to have their functionality lower in the hierarchy—a base class specifies one or more abstract methods that must be declared for each concrete class in the hierarchy, and the individual derived classes override these methods to provide derived-class-specific implementations.

20 11.5.1 Creating Abstract Base Class Employee
Earnings() is declared abstract No implementation can be given for Earnings() in the Employee abstract class An array of Employee variables will store references to derived class objects Earnings method calls from these variables will call the appropriate version of the Earnings method

21 Fig. 11.2 | Employee hierarchy UML class diagram.

22 Fig. 11.3 | Polymorphic interface for the Employee hierarchy classes.

23 Outline Declare abstract class Employee (1 of 2)
Employee.cs (1 of 2) Attributes common to all employees

24 Outline (2 of 2) abstract method Earnings has no implementation
Employee.cs (2 of 2) abstract method Earnings has no implementation

25 11.5.2 Creating Concrete Derived Class SalariedEmployee
Concrete class Inherits from Abstract Employee class Override Earnings weeklySalary

26 Outline Class SalariedEmployee extends class Employee (1 of 2)
SalariedEmployee .cs (1 of 2) Call base class constructor Validate and set weekly salary value

27 Outline Override Earnings method so SalariedEmployee can be concrete
SalariedEmployee .cs (2 of 2) Override Earnings method so SalariedEmployee can be concrete Override ToString method Call base class’s version of ToString

28 11.5.3 Creating Concrete Derived Class HourlyEmployee
Concrete class Inherits from Abstrict Employee class Overrides Earnings wage and hours

29 Outline Class HourlyEmployee extends class Employee (1 of 3)
HourlyEmployee.cs (1 of 3) Call base class constructor Validate and set hourly wage value

30 Outline Validate and set hours worked value (2 of 3)
HourlyEmployee.cs (2 of 3) Override Earnings method so HourlyEmployee can be concrete

31 Outline Override ToString method (3 of 3)
HourlyEmployee.cs (3 of 3) Call base class’s ToString method

32 11.5.4 Creating Concrete Derived Class CommisionEmployee
Concrete class Inherits from Abstract Employee class Override Earnings grossSales and commissionRate

33 Outline Class CommissionEmployee extends class Employee (1 of 2)
CommissionEmployee .cs (1 of 2) Call base class constructor Validate and set commission rate value

34 Outline Validate and set the gross sales value (2 of 2)
CommissionEmployee .cs (2 of 2) Override Earnings method so CommissionEmployee can be concrete Override ToString method Call base class’s ToString method

35 11.5.5 Creating Indirect Concrete Derived Class BasePlusCommisionEmployee
Inherits from class CommissionEmployee Therefore is an indirect derived class of class Employee

36 Outline Class BasePlusCommissionEmployee extends class CommissionEmployee BasePlusCommission Employee.cs (1 of 2) Call base class constructor Validate and set base salary value

37 Outline Override Earnings method Call base class’s Earnings method
BasePlusCommission Employee.cs (2 of 2) Override ToString method Call base class’s ToString method

38 11.5.6 Polymorphic Processing, Operator is and Downcasting
Dynamic binding Also known as late binding Calls to overridden methods are resolved at execution time, based on the type of object referenced is operator Determines if a particular object is of a certain type or a derived class of that type

39 Outline (1 of 5) Create objects of various type from this sections
PayrollSystemTest. cs (1 of 5) Create objects of various type from this sections

40 Outline PayrollSystemTest. cs (2 of 5) Assigning derived class objects to base class variables

41 Outline If the currentEmployee variable points to a BasePlusCommissionEmployee object PayrollSystemTest. cs (3 of 5) Downcast currentEmployee to a BasePlusCommissionEmployee reference Give BasePlusCommissionEmployees a 10% base salary bonus Polymorphically call Earnings method Call GetType method to display each Employee derived class object’s class name

42 Outline PayrollSystemTest. cs (4 of 5)

43 Outline PayrollSystemTest. cs (5 of 5)

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

45 Software Engineering Observation 11.4
If 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.

46 Common Programming Error 11.4
When 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.

47 11.5.6 Polymorphic Processing, Operator is and Downcasting (Cont.)
GetType method Return an object of class Type Contains information on: Object’s type Class name public methods Name of its base class Downcasting Convert a reference to a base class to a reference to a derived class Allowed only if the object has an is-a relationship with the derived class

48 11.5.7 Summary of the Allowed Assignments Between Base Class and Derived Class Variables
Base class and derived class assignment rules Assigning a base class reference to a base class variable is straightforward Assigning a derived class reference to a derived variable is straightforward Assigning a derived class reference to a base class variable is safe because of the is-a relationship Referring to derived class-only members through base class variables is a compilation error Assigning a base class reference to a derived class variable is a compilation error Downcasting can get around this error The is operator can be used to ensure cast is performed only is the object is a derived class object

49 11.6 sealed Methods and Classes
Cannot be overridden in a derived class private and static methods are implicitly sealed sealed methods are resolved at compile time, this is known as static binding Compilers can optimize by inlining the code sealed classes Cannot be extended by a derived class All methods in a sealed class are implicitly sealed

50 Performance Tip 11.1 The 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.

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

52 Software Engineering Observation 11.5
In the FCL, the vast majority of classes are not declared sealed. This enables inheritance and polymorphism—the fundamental capabilities of object-oriented programming.

53 11.7 Case Study: Creating and Using Interfaces
Keyword interface Contains only constants and abstract methods All fields are implicitly public, static and sealed All methods are implicitly public abstract methods Classes can implement interfaces Use the colon (“:”) operator The class must declare each method in the interface using the same signature or the class must be declared abstract Typically used when disparate classes need to share common methods and constants Normally declared in their own files with the same names as the interfaces and with the .cs file-name extension

54 Common Programming Error 11.6
It 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.

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

56 11.7.1 Developing a IPayable Hierarchy
IPayable interface Contains method GetPaymentAmount Is implemented by the Invoice and Employee classes UML representation of interfaces Interfaces are distinguished from classes by placing the word “interface” in guillemets (« and ») above the interface name The relationship between a class and an interface is known as realization A class “realizes” the method of an interface

57 Good Programming Practice 11.1
By convention, the name of an interface begins with "I". This helps distinguish interfaces from classes, improving code readability.

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

59 Fig. 11.10 | IPayable interface and class hierarchy UML class diagram.

60 Outline Declare interface IPayable
IPayable.cs Declare GetPaymentAmount method which is implicitly public and abstract

61 11.7.3 Creating Class Invoice
A class can implement as many interfaces as it needs Use a comma-separated list of interface names after keyword implements Example: public class ClassName : BaseClassName, FirstInterface, SecondInterface, …

62 Outline Class Invoice implements interface IPayable (1 of 4)
Invoice.cs (1 of 4)

63 Outline Invoice.cs (2 of 4)

64 Outline Invoice.cs (3 of 4)

65 Outline Invoice.cs (4 of 4) Declare GetPaymentAmount to fulfill contract with interface IPayable

66 11.7.4 Modifying Class Employee to Implement Interface IPayable
Implements IPayable Rename Earnings to GetPaymentAmount

67 Outline Class Employee implements interface IPayable (1 of 2)
Employee.cs (1 of 2)

68 Outline (2 of 2) GetPaymentAmount method is not implemented here
Employee.cs (2 of 2) GetPaymentAmount method is not implemented here

69 11.7.5 Modifying Class SalariedEmployee for Use in the IPayable Hierarchy
Objects of any derived classes of the class that implements the interface can also be thought of as objects of the interface A reference to a derived class object can be assigned to an interface variable if the base class implements that interface

70 Outline Class SalariedEmployee extends class Employee (which implements interface IPayable) SalariedEmployee .cs (1 of 2)

71 Outline Declare GetPaymentAmount method instead of Earnings method
SalariedEmployee .cs (2 of 2)

72 Software Engineering Observation 11.6
Inheritance 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. An object of any derived classes of a class that implements an interface also can be thought of as an object of the interface type.

73 Software Engineering Observation 11.7
The 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. When a method parameter receives a variable of a base class or interface type, the method polymorphically processes the object received as an argument.

74 11.7.6 Using Interface IPayable to Process Invoices and Employees Polymorphically
Module PayableInterfaceTest Array of type IPayable Able to hold any objects that implements IPayable

75 Software Engineering Observation 11.8
All methods of class object can be called by using a reference of an interface type—the reference refers to an object, and all objects inherit the methods of class object.

76 Outline Declare array of IPayable variables (1 of 2)
PayableInterfaceTe st.cs (1 of 2) Assigning references to Invoice objects to IPayable variables Assigning references to SalariedEmployee objects to IPayable variables

77 Outline PayableInterfaceTe st.cs (2 of 2) Call ToString and GetPaymentAmount methods polymorphically

78 11.7.7 Common Interfaces of the .NET Framework Class Library
Interfaces in .NET FCL These interfaces enable you to extend many important aspects of C#

79 Fig. 11. 16 | Common interfaces of the. Net Framework Class Library
Fig | Common interfaces of the .Net Framework Class Library. (Part 1 of 2)

80 Fig. 11. 16 | Common interfaces of the. Net Framework Class Library
Fig | Common interfaces of the .Net Framework Class Library. (Part 2 of 2)

81 11.8 Operator Overloading Operator Overloading
Enable operators to work with class objects C# allow overloading for most operators Keyword operator followed by the operator Example: operator+ Must be public and static

82 Software Engineering Observation 11.9
Use operator overloading when it makes an application clearer than accomplishing the same operations with explicit method calls.

83 Outline ComplexNumber.cs (1 of 3)

84 Outline ComplexNumber.cs (2 of 3)

85 Outline ComplexNumber.cs (3 of 3) Overload operators +, -, *

86 Software Engineering Observation 11.10
Overload operators to perform the same function or similar functions on class objects as the operators perform on objects of simple types. Avoid non-intuitive use of operators.

87 Software Engineering Observation 11.11
At 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.

88 Outline (1 of 2) Declare two ComplexNumbers
Operator Overloading.cs (1 of 2) Declare two ComplexNumbers Initializes the two ComplexNumbers

89 Outline Use the overloaded operators Operator Overloading.cs (2 of 2)

90 11.9 (Optional) Software Engineering Case Study: Incorporating Inheritance into the ATM System
UML model for inheritance The generalization relationship The base class is a generalization of the derived classes The derived classes are specializations of the base class Transaction base class Contains the methods and fields BalanceInquiry, Withdrawal and Deposit have in common Execute method accountNumber field

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

92 Fig. 11. 20 | Class diagram modeling the generalization (i. e
Fig | Class diagram modeling the generalization (i.e., inheritance) relationship between the base class Transaction and its derived classes BalanceInquiry, Withdrawal and Deposit.

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

94 Fig. 11.22 | Class diagram after incorporating inheritance into the system.

95 Software Engineering Observation 11.12
A 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 (as in Figs. 11.21 and 11.22), a good practice that promotes readability is to divide this information between two class diagrams—one focusing on associations and the other on attributes and operations. When examining classes modeled in this fashion, it is crucial to consider both class diagrams to get a complete picture of the classes. For example, one must refer to Fig. 11.21 to observe the inheritance relationship between Transaction and its derived classes; that relationship is omitted from Fig. 11.22.

96 11.9 (Optional) Software Engineering Case Study: Incorporating Inheritance into the ATM System (Cont.) Incorporating inheritance into the ATM system design If class A is a generalization of class B, then class B extends class A If class A is an abstract class and class B is a derived class of class A, then class B must implement the abstract methods of class A if class B is to be a concrete class

97 Outline Derived class Withdrawal extends base class Transaction
Withdrawal.cs Derived class Withdrawal extends base class Transaction

98 Outline Derived class Withdrawal extends base class Transaction
Withdrawal.cs

99 Outline Declare abstract base class Transaction (1 of 2)
Transaction.cs (1 of 2)

100 Outline Transaction.cs (2 of 2) Declare abstract method Execute


Download ppt "Polymorphism, Interfaces & Operator Overloading"

Similar presentations


Ads by Google