1 / 96

Polymorphism, Interfaces & Operator Overloading

Learn how polymorphism enables flexibility in programming, including abstract classes, interfaces, and method overloading. Discover the power of polymorphic behavior and its impact on system extensibility. Explore real-world examples and case studies to deepen your understanding.

wayman
Download Presentation

Polymorphism, Interfaces & Operator Overloading

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 12 • Polymorphism, Interfaces & Operator Overloading

  2. 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

  3. 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

  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.

  5. 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.

  6. 12.1   Introduction • 12.2   Polymorphism Examples • 12.3   Demonstrating Polymorphic Behavior • 12.4   Abstract Classes and Methods • 12.5   Case Study: Payroll System Using Polymorphism • 12.6   sealed Methods and Classes • 12.7   Case Study: Creating and Using Interfaces • 12.8   Operator Overloading • 12.9   (Optional) Software Engineering Case Study: Incorporating Inheritance and Polymorphisminto the ATM System

  7. 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.

  8. 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.

  9. 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 La­serBeam. • 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.

  10. 12.2  Polymorphism Examples (Cont.) Software Engineering Observation 12.1 Polymorphism 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.

  11. 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.

  12. 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

  13. Outline • The example in Fig. 12.1 demonstrates three waysto use base-class and derived-class variables. PolymorphismTest.cs (1 of 3 ) Create a new CommissionEmployee3 object and assign its reference to a CommissionEmployee3 variable. Fig. 12.1|Assigning base-class and derived-class referencesto base-class and derived-class variables. (Part 1 of 3.)

  14. Outline 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. Fig. 12.1|Assigning base-class and derived-class referencesto base-class and derived-class variables. (Part 2 of 3.)

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

  16. 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.

  17. 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.

  18. 12.4  Abstract Classes and Methods (Cont.) • 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.

  19. 12.4  Abstract Classes and Methods (Cont.) • abstract property declarations have the form: public abstract PropertyTypeMyProperty {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.

  20. 12.4  Abstract Classes and Methods (Cont.) • Constructors and static methods cannot be declared abstract. Software Engineering Observation 12.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 classesmust override.

  21. 12.4  Abstract Classes and Methods (Cont.) Common Programming Error 12.1 Attempting to instantiate an object of an abstractclass is a compilation error. Common Programming Error 12.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.

  22. 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.

  23. 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.

  24. 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.

  25. 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

  26. 12.5  Case Study: Payroll System Using Polymorphism (Cont.) Software Engineering Observation 12.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. Hierarchies designed for interface inheritance tend to have their functionality lower in the hierarchy.

  27. 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

  28. 12.5  Case Study: Payroll System Using Polymorphism (Cont.) • 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. Fig. 12.3|Polymorphic interface for the Employee hierarchy classes.

  29. Outline • The Employee class’s declaration is shown in Fig. 12.4. Employee.cs (1 of 2 ) Fig. 12.4|Employee abstract base class. (Part 1 of 2.)

  30. Outline Employee.cs (1 of 2 ) The Employee class includes an abstract method Earnings, which must be implemented by concrete derived classes. Fig. 12.4|Employee abstract base class. (Part 2 of 2.)

  31. Outline SalariedEmployee.cs (1 of 2 ) SalariedEmployee extends Employee. Using the base class constructor to initialize the private variables not inherited from the base class. Fig. 12.5|SalariedEmployee class that extendsEmployee. (Part 1 of 2.)

  32. Outline 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. Fig. 12.5|SalariedEmployee class that extendsEmployee. (Part 2 of 2.)

  33. Outline • Class HourlyEmployee (Fig. 12.6) also extends class Employee. HourlyEmployee.cs (1 of 3 ) Fig. 12.6|HourlyEmployee class that extendsEmployee. (Part 1 of 3.)

  34. Outline 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). Fig. 12.6|HourlyEmployee class that extendsEmployee. (Part 2 of 3.)

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

  36. Outline • Class CommissionEmployee (Fig. 12.7) extends class Employee. CommissionEmployee.cs (1 of 3 ) Fig. 12.7|CommissionEmployee class thatextends Employee. (Part 1 of 3.)

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

  38. Outline CommissionEmployee.cs (3 of 3 ) Calling base-class method ToString to obtain the Employee-specific information. Fig. 12.7|CommissionEmployee class thatextends Employee. (Part 3 of 3.)

  39. Outline • Class BasePlusCommissionEmployee (Fig. 12.8) extends class Commission­Employee and therefore is an indirect derived class of class Employee. BasePlusCommissionEmployee.cs (1 of 2 ) Fig. 12.8|BasePlusCommissionEmployee class that extends CommissionEmployee. (Part 1 of 2.)

  40. Outline 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. Fig. 12.8|BasePlusCommissionEmployee class that extends CommissionEmployee. (Part 2 of 2.)

  41. Outline • The application in Fig. 12.9 tests our Employee hierarchy. PayrollSystemTest.cs (1 of 6 ) Create objects of each of the four concrete Employee derived classes. Fig. 12.9|Employee hierarchy test application. (Part 1 of 6.)

  42. Outline PayrollSystemTest.cs (2 of 6 ) Each object’s ToString method is called implicitly. Fig. 12.9|Employee hierarchy test application. (Part 2 of 6.)

  43. Outline 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. Fig. 12.9|Employee hierarchy test application. (Part 3 of 6.)

  44. Outline 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. Fig. 12.9|Employee hierarchy test application. (Part 4 of 6.)

  45. Outline PayrollSystemTest.cs (5 of 6 ) Fig. 12.9|Employee hierarchy test application. (Part 5 of 6.)

  46. Outline PayrollSystemTest.cs (6 of 6 ) Fig. 12.9|Employee hierarchy test application. (Part 6 of 6.)

  47. 12.5  Case Study: Payroll System Using Polymorphism (Cont.) Common Programming Error 12.3 Assigning a base-class variable to a derived-class variable (without an explicit downcast) is a compilation error. Software Engineering Observation 12.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.

  48. 12.5  Case Study: Payroll System Using Polymorphism (Cont.) Common Programming Error 12.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.

  49. 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.

  50. 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.

More Related