 2002 Prentice Hall. All rights reserved.

Slides:



Advertisements
Similar presentations
2006 Pearson Education, Inc. All rights reserved Object-Oriented Programming: Polymorphism.
Advertisements

 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - Object-Oriented Programming: Polymorphism Outline 10.1 Introduction 10.2 Relationships Among.
Chapter 20- Virtual Functions and Polymorphism Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng.
 2002 Prentice Hall. All rights reserved. 1 Chapter 9 – Object-Oriented Programming: Inheritance Outline 9.1Introduction 9.2Base Classes and Derived Classes.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
 2002 Prentice Hall. All rights reserved. Some slides modified by LL 1 Chapter 9 – Object-Oriented Programming: Inheritance Outline 9.1Introduction 9.2Base.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 20- Virtual Functions and Polymorphism Outline 20.1Introduction 20.2Type Fields and switch Statements.
1 Evan Korth New York University abstract classes and casting Professor Evan Korth New York University.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
 2002 Prentice Hall. All rights reserved. 1 Chapter 10 – Object-Oriented Programming: Polymorphism Outline 10.1 Introduction 10.2 Derived-Class-Object.
C++ Polymorphism Systems Programming. Systems Programming: Polymorphism 2   Polymorphism Examples   Relationships Among Objects in an Inheritance.
 Simple payroll application that polymorphically calculates the weekly pay of several different types of employees using each employee’s Earnings method.
1 Abstract Class There are some situations in which it is useful to define base classes that are never instantiated. Such classes are called abstract classes.
Object Oriented Concepts
Interfaces Need arising from software engineering –Disparate groups of programmers need to agree to a “contract” that spells out how their software interacts.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
Lecture 9 Polymorphism Richard Gesick.
1 Object-Oriented Programming: Polymorphism 10.1 Introduction 10.2 Relationships Among Objects in an Inheritance Hierarchy Invoking Superclass Methods.
1 Advanced Programming Lecture 5 Inheritance. 2 static Class Members Every object of a class has its own copy of all instance variables Sometimes it is.
 2002 Prentice Hall. All rights reserved. 1 Chapter 9 – Object-Oriented Programming: Inheritance Outline 9.1Introduction 9.2Base Classes and Derived Classes.
 2002 Prentice Hall. All rights reserved. 1 Chapter 10 – Object-Oriented Programming: Polymorphism Outline 10.1 Introduction 10.2 Derived-Class-Object.
 2002 Prentice Hall. All rights reserved. 1 Chapter 9 – Object-Oriented Programming: Inheritance Outline 9.1Introduction 9.2 Base Classes and Derived.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
1 OOP : main concepts Polymorphism. 2 OOP : main concepts  The main concepts:  In a superclass –public members Accessible anywhere program has a reference.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 20 - C++ Virtual Functions and Polymorphism.
 2006 Pearson Education, Inc. All rights reserved Polymorphism, Interfaces & Operator Overloading.
 All calls to method toString and earnings are resolved at execution time, based on the type of the object to which currentEmployee refers.  Known as.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 9 - Inheritance Outline 9.1Introduction 9.2Inheritance: Base Classes and Derived Classes 9.3.
 2002 Prentice Hall. All rights reserved. 1 Introduction Polymorphism allows programmers to write: –Programs that handle a wide variety of related classes.
 2006 Pearson Education, Inc. All rights reserved Polymorphism, Interfaces & Operator Overloading.
Java Programming Dr. Randy Kaplan. Abstract Classes and Methods.
1 The finalize, clone, and getClass Methods  The finalize method is invoked by the garbage collector on an object when the object becomes garbage.  The.
Object Oriented Programming
 2002 Prentice Hall. All rights reserved. 1 Chapter 10 – Object-Oriented Programming: Polymorphism Outline 10.1 Introduction 10.2 Derived-Class-Object.
 Pearson Education, Inc. All rights reserved Object-Oriented Programming: Polymorphism.
1 Advanced Programming Inheritance (2). 2 Inheritance Inheritance allows a software developer to derive a new class from an existing one The existing.
 2002 Prentice Hall. All rights reserved. 1 Chapter 10 – Object-Oriented Programming: Part 2 Outline 10.1Introduction 10.2 Derived-Class-Object to Base-Class-Object.
 2002 Prentice Hall. All rights reserved. 1 Chapter 11 – [Object-Oriented Programming] Polymorphism, Interfaces & Operator Overloading Section [order.
 2009 Pearson Education, Inc. All rights reserved Polymorphism, Interfaces & Operator Overloading.
Inheritance ndex.html ndex.htmland “Java.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 20 - Virtual Functions Outline 20.1Introduction 20.2Type Fields and switch Statements 20.3Virtual.
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
Object-Oriented Programming: Polymorphism Chapter 10.
Jozef Goetz contribution, Credits go to  2014, 2011, 2009 Pearson Education, Inc. All rights reserved.  2002 Prentice Hall. All rights reserved.
 2009 Prentice Hall. All rights reserved. 1 Chapter 12 Polymorphism, Interfaces & Operator Overloading [optional] Many slides modified by Prof. L. Lilien.
 2002 Prentice Hall. All rights reserved. Page 1 Inheritance: Object-Oriented Programming Outline 9.1 Introduction 9.2 Superclasses and Subclasses 9.3.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - Object-Oriented Programming: Polymorphism.
 2006 Pearson Education, Inc. All rights reserved Object-Oriented Programming: Polymorphism.
C++ How to Program, 7/e. © by Pearson Education, Inc. All Rights Reserved.2.
C++ How to Program, 7/e.  There are cases in which it’s useful to define classes from which you never intend to instantiate any objects.  Such classes.
Object-Oriented Programming: Polymorphism
Chapter 12 OOP: Polymorphism, Interfaces and Operator Overloading
Polymorphism, Interfaces & Operator Overloading
Questions from last lesson
Chapter 9 – Object-Oriented Programming: Inheritance
Polymorphism, Interfaces & Operator Overloading
abstract classes and casting objects
Object-Oriented Programming: Polymorphism
Object-Oriented Programming: Polymorphism
Lecture 23 Polymorphism Richard Gesick.
Object-Oriented Programming: Polymorphism
Chapter 9 Object-Oriented Programming: Inheritance
Week 6 Object-Oriented Programming (2): Polymorphism
Chapter 20- Virtual Functions and Polymorphism
Polymorphism, Interfaces &
Object-Oriented Programming: Polymorphism
Chapter 20 - C++ Virtual Functions and Polymorphism
Polymorphism and Type Casting
Presentation transcript:

 2002 Prentice Hall. All rights reserved. Chapter 12 – Polymorphism, Interfaces & Operator Overloading Part I Credits go to  2014, 2011, 2009 Pearson Education, Inc. All rights reserved.  2002 Prentice Hall. All rights reserved.

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 General propositions do not decide concrete cases. Oliver Wendell Holmes

Chapter 12 –Polymorphism, Interfaces & Operator Overloading Outline Introduction Derived-Class-Object to Base-Class-Object Conversion Type Fields and switch Statements Polymorphism Examples Abstract Classes and Methods Case Study: Inheriting Interface and Implementation sealed Classes and Methods Case Study: Payroll System Using Polymorphism Case Study: Creating and Using Interfaces Delegates Operator Overloading

To understand the concept of polymorphism Objectives To understand the concept of polymorphism To understand how polymorphism makes systems extensible and maintainable. To understand the distinction between abstract classes and concrete classes. To learn how to create sealed classes, interfaces and delegates.

Polymorphism allows programmers to write: 12.1 Introduction Polymorphism allows programmers to write: Programs that handle a wide variety of related classes in a generic manner the programmer can deal in generalities and let the executing program concern itself with the specifics. Makes it possible to design and implement systems that are easily extensible new classes can be added with little or no modification to the generic portions of the program

12.2 Polymorphism Examples For example, base-class Shape derived-classes Circle, Rectangle and Square Each class draws itself according to type of class Shape has method draw Each subclass (derived class) overrides method draw Call method draw of base-class Shape Program determines dynamically which subclass draw method to invoke At execution time, program determines to which object the reference is actually pointing

12.2 Polymorphism Examples Quadrilateral base-class Rectangle derived-class Square derived-class Parallelogram derived-class Trapezoid derived-class Rectangle "is a" Quadrilateral getPerimeter(or area) method can be performed on any derived-class: Square, Parallelogram, Trapezoid public class Square {getPerimeter(){} } public class Parallelogram {getPerimeter(){} } Same method takes on "many forms" - polymorphism Have an array of base-class references Array would point to all the objects Call getPerimeter using the base-class references Appropriate method called for each class Method perimeter might need to be invoked on all classes s.getPerimeter(); // s – base-class reference refers to a proper // derived-class object C# polymorphically chooses the correct overriding method in the derived-class from which the object is instantiated Adding a new derived-class easily Simply need to define getPerimeter for that class Can refer to it with a base-class reference Can use same base-class array as before - "fits right in"

12.2 Polymorphism Examples SpaceObject base-class – contains method DrawYourself Martian derived-class (implements DrawYourself) Venutian derived-class (implements DrawYourself) Plutonian derived-class (implements DrawYourself) SpaceShip derived-class (implements DrawYourself) A screen-manager program may contain a SpaceObject array of references to objects of various classes that derive from SpaceObject To refresh the screen, the screen-manager calls DrawYourself on each object in the array The program polymorphically calls the appropriate version of DrawYourself on each object, based on the type of that object

12.3 Demonstrating Polymorphic Behavior An object of a derived-class can be treated as an object of its base-class this enables to create An array of base-class references that refer to objects of many derived-class types this is allowed despite the fact that the derived-class objects are of different data type Base-class object is NOT an object of any of its derived classes Assigning a base-class reference to a derived-class reference causes InvalidCastException Class hierarchies Can assign derived-class objects to base-class references and manipulate the object as that type Can explicitly cast between types in a class hierarchy

Definition of class Point 1 // Fig. 10.1 ed1: Point.cs 2 // Point class represents an x-y coordinate pair. 3 4 using System; 5 6 // Point class definition implicitly inherits from Object 7 public class Point 8 { 9 // point coordinate 10 private int x, y; 11 12 // default constructor 13 public Point() 14 { 15 // implicit call to Object constructor occurs here 16 } 17 18 // constructor 19 public Point( int xValue, int yValue ) 20 { 21 // implicit call to Object constructor occurs here 22 X = xValue; 23 Y = yValue; 24 } 25 26 // property X 27 public int X 28 { 29 get 30 { 31 return x; 32 } 33 Definition of class Point Point.cs

Point.cs 34 set 35 { 36 x = value; // no need for validation 37 } 38 35 { 36 x = value; // no need for validation 37 } 38 39 } // end property X 40 41 // property Y 42 public int Y 43 { 44 get 45 { 46 return y; 47 } 48 49 set 50 { 51 y = value; // no need for validation 52 } 53 54 } // end property Y 55 56 // return string representation of Point 57 public override string ToString() 58 { 59 return "[" + X + ", " + Y + "]"; 60 } 61 62 } // end class Point Point.cs

Definition of class Circle which inherits from class Point 1 // Fig. 10.2 ed1: Circle.cs 2 // Circle class that inherits from class Point. 3 4 using System; 5 6 // Circle class definition inherits from Point public class Circle : Point //each Circle object “is a” Point // and has a radius represented via property Radius 8 { 9 private double radius; // circle's radius 10 11 // default constructor 12 public Circle() 13 { 14 // implicit call to Point constructor occurs here 15 } 16 17 // constructor 18 public Circle( int xValue, int yValue, double radiusValue ) 19 : base( xValue, yValue ) 20 { 21 Radius = radiusValue; 22 } 23 24 // property Radius 25 public double Radius 26 { 27 get 28 { 29 return radius; 30 } 31 Definition of class Circle which inherits from class Point Circle.cs

Circle.cs 32 set 33 { 34 if ( value >= 0 ) // validate radius 33 { 34 if ( value >= 0 ) // validate radius 35 radius = value; 36 } 37 38 } // end property Radius 39 40 // calculate Circle diameter 41 public double Diameter() 42 { 43 return Radius * 2; 44 } 45 46 // calculate Circle circumference 47 public double Circumference() 48 { 49 return Math.PI * Diameter(); 50 } 51 52 // calculate Circle area 53 public virtual double Area() 54 { 55 return Math.PI * Math.Pow( Radius, 2 ); 56 } 57 58 // return string representation of Circle 59 public override string ToString() 60 { 61 return "Center = " + base.ToString() + 62 "; Radius = " + Radius; 63 } 64 65 } // end class Circle Circle.cs

Use base-class reference to access a derived-class object 1 // Fig. 10.3 ed1: PointCircleTest.cs // Demonstrating inheritance and polymorphism // by using the assignment and cast operations. 3 4 using System; 5 using System.Windows.Forms; 6 7 // PointCircleTest class definition 8 class PointCircleTest 9 { 10 // main entry point for application. 11 static void Main( string[] args ) 12 { // Assign a base-class reference to a base-class-type variable (object) 13 Point point1 = new Point( 30, 50 ); // Assign a derived-class reference to derived-class-type variable (object) 14 Circle circle1 = new Circle( 120, 89, 2.7 ); 15 16 string output = "Point point1: " + point1.ToString() + 17 "\nCircle circle1: " + circle1.ToString(); 18 19 // use 'is a' relationship to assign derived-class references 20 // Circle circle1 to base-class reference Point 21 Point point2 = circle1; 22 23 output += "\n\nCCircle circle1 (via point2): " + 24 point2.ToString(); // the methods which is called //is based on the referred object type (not the reference type) 25 // this is an example of polymorphism – see next sections 26 // downcast BACK to Circle (cast base-class reference point2 to // derived-class reference Circle circle2) 28 Circle circle2 = ( Circle ) point2; // If a derived-class object has been assigned to a reference of one of its direct or indirect base (see line 21) classes, it is acceptable to cast that base-class reference back to a reference of the derived-class type (see also line 37). output += "\n\nCircle circle1 (via circle2): " + 31 circle2.ToString(); 32 33 output += "\nArea of circle1 (via circle2): " + 34 circle2.Area().ToString( "F" ); // F is 2 decimal places 35 PointCircleTest.cs Create a Point object Create a Circle object Use base-class reference to access a derived-class object Use derived-class reference to access circle1 object

PointCircleTest.cs Program Output Test if point1 references a Circle object – Improper case since point1 references a Point object 36 // attempt to assign point1 object to Circle reference 37 if ( point1 is Circle ) // true if the left operand is a reference to 38 { // an instance of the right operand or a derived class 39 circle2 = ( Circle ) point1; // objects can be cast only to // their own type or to their base-class types 40 output += "\n\ncast successful"; 41 } 42 else 43 { 44 output += "\n\npoint1 does not refer to a Circle"; 45 } 46 47 MessageBox.Show( output, 48 "Demonstrating the 'is a' relationship" ); 49 50 } // end method Main 51 52 } // end class PointCircleTest PointCircleTest.cs Program Output

errors Assigning a base-class object (or a base-class reference) to a derived-class reference (without an explicit cast) is a syntax error. Attempting to cast a base-class reference to a derived-class reference causes an InvalidCastException if the reference refers to a base-class object rather than an appropriate derived-class object. After assigning a derived-class object to a base-class reference, attempting to reference derived-class-only members with the base-class reference is a compilation error!!!

Implicit Base-class-Object-to-Derived-class-Object Conversion derived-class reference and base-class reference Implicit conversion base-class reference to derived-class reference derived-class object “is a” base-class object through inheritance Four ways to mix and match references Refer to a derived-class object with a derived-class reference Refer to a base-class object with a base-class reference Refer to a derived-class object with a base-class reference (e.g. public class Circle : Point{} Point point; Circle circle; point = circle ) So a base-class reference cannot refer to derived-class-only members !!! 4. Refer to a base-class object with a derived-class reference – see a below: Point point; Circle circle; must first be cast to a derived-class reference as below otherwise syntax error Circle circle = (Circle) point;

Derived-Class-Object to Base-Class-Object Conversion Store references to derived-class and base-class objects: Both straightforward Assign a derived-class reference to a derived-class-type variable (object) Assign a base-class reference to a base-class-type variable (object) Assign a derived-class reference variable to a base-class variable is safe and logical “is a” relationship: an object of a derived-class can be treated as an object of its base-class b/c the derived class contains all members of the base class

Type Fields and Switch Statements Can be used to deal with many objects of different types Appropriate action based on object’s type e.g. in a hierarchy of shapes in which each shape object has a ShapeType property, a switch structure could employ the object’s ShapeType to determine which Print method to call. Problems using switch logic Programmer may forget to include a type Might forget to test all possible cases Every addition/deletion of a class requires all switch statements to be changed Tracking all these changes is time consuming and error prone How can we eliminate the need for switch logic Avoids all these problems automatically by providing polymorphism mechanism: switching between objects at run time

Dynamic Method Binding Implements polymorphic processing of objects Use base-class reference to refer to derived-class object Program chooses “correct” method in derived class At execution time, method calls routed to appropriate method With polymorphism New classes can be added easily One method call can cause different actions to occur, depending on object receiving call

12.4 Abstract Classes and Methods Cannot be instantiated Too generic to define real objects Used as base classes from which other classes may inherit (concrete classes) Incomplete derived-classes fill in "missing pieces“ Can contain abstract methods ([holders] and/or abstract properties Have no implementation Derived classes must override inherited abstract methods and properties to enable instantiation

12.4 Abstract Classes and Methods Abstract classes not required, but reduce client code dependencies Can create references to abstract classes at compilation time Cannot instantiate objects of abstract classes abstract class and method – a common interface used by various members of a class hierarchy Declare with keyword abstract Contain one or more abstract methods with no implementation public abstract void draw(); public abstract class A { A() {} m1(){} m2(){} public abstract m3(){}} Any class with an abstract method must be abstract abstract methods must be overridden in derived class Otherwise, derived class must be abstract

12.4 Abstract Classes and Methods Concrete classes Classes from which objects are instantiated Provide specifics for instantiating objects Square, Circle and Triangle use the keyword override to provide implementations for all the abstract methods and properties of the base-class Class hierarchies Most general classes are usually abstract Any class with an abstract method or property must be declared abstract Even though abstract classes cannot be instantiated, we can use abstract class references to refer to instances of any concrete class derived from the abstract class

Case Study: Inheriting Interface and Implementation Shape hierarchy class diagram Circle Cylinder Point Shape

Case Study: Inheriting Interface and Implementation Abstract base class Shape Concrete virtual method Area (default return value is 0) Concrete virtual method Volume (default return value is 0) Abstract read-only property Name Class Point2 inherits from Shape Overrides property Name (required) Does NOT override methods Area and Volume Class Circle2 inherits from Point2 Overrides property Name Overrides method Area, but not Volume Class Cylinder2 inherits from Circle2 Overrides methods Area and Volume

Case Study: Inheriting Interface and Implementation abstract base-class Shape Abstract method (must be implemented) property Name, Default implementation does not make sense non-abstract methods Area (return 0) Volume (return 0.0) If not overridden, uses derived-class default implementation Shape <-Point <- Circle <- Cylinder hierarchy Polymorphism example uses an array of object references Class Shape used to define a set of common methods Interface is common methods: Area(), Volume()and property public abstract string Name; Implementation of Area and Volume used for first levels of hierarchy

Declaration of abstract class Shape 1 // Fig. 10.4 ed1: Shape.cs 2 // Demonstrate a shape hierarchy using an abstract base class. 3 using System; 4 5 public abstract class Shape 6 { 7 // return Shape's area 8 public virtual double Area() 9 { 10 return 0; 11 } 12 13 // return Shape's volume 14 public virtual double Volume() 15 { 16 return 0; 17 } 18 19 // return Shape's name 20 public abstract string Name 21 { 22 get; 23 } 24 } Shape.cs Declaration of abstract class Shape Declaration of virtual methods Area and Volume with default implementations Declaration of read-only abstract property Name; implementing classes will have to provide an implementation for this property

Class Point2 inherits from class Shape 1 // Fig. 10.5 ed1: Point2.cs 2 // Point2 inherits from abstract class Shape and represents 3 // an x-y coordinate pair. 4 using System; 5 6 // Point2 inherits from abstract class Shape 7 public class Point2 : Shape 8 { 9 private int x, y; // Point2 coordinates 10 11 // default constructor 12 public Point2() 13 { 14 // implicit call to Object constructor occurs here 15 } 16 17 // constructor 18 public Point2( int xValue, int yValue ) 19 { 20 X = xValue; 21 Y = yValue; 22 } 23 24 // property X 25 public int X 26 { 27 get 28 { 29 return x; 30 } 31 32 set 33 { 34 x = value; // no validation needed 35 } Point2.cs Class Point2 inherits from class Shape

Point2’s implementation of the read-only Name property 36 } 37 38 // property Y 39 public int Y 40 { 41 get 42 { 43 return y; 44 } 45 46 set 47 { 48 y = value; // no validation needed 49 } 50 } 51 52 // return string representation of Point2 object 53 public override string ToString() 54 { 55 return "[" + X + ", " + Y + "]"; 56 } 57 58 // implement abstract property Name of class Shape 59 public override string Name 60 { 61 get 62 { 63 return "Point2"; 64 } 65 } 66 67 } // end class Point2 Point2.cs Point2’s implementation of the read-only Name property

Definition of class Circle2 which inherits from class Point2 1 // Fig. 10.6 ed1: Circle2.cs 2 // Circle2 inherits from class Point2 and overrides key members. 3 using System; 4 5 // Circle2 inherits from class Point2 6 public class Circle2 : Point2 7 { 8 private double radius; // Circle2 radius 9 10 // default constructor 11 public Circle2() 12 { 13 // implicit call to Point2 constructor occurs here 14 } 15 16 // constructor 17 public Circle2( int xValue, int yValue, double radiusValue ) 18 : base( xValue, yValue ) 19 { 20 Radius = radiusValue; 21 } 22 23 // property Radius 24 public double Radius 25 { 26 get 27 { 28 return radius; 29 } 30 Circle2.cs Definition of class Circle2 which inherits from class Point2

Override the Area method (defined in class Shape) 31 set 32 { 33 // ensure non-negative radius value 34 if ( value >= 0 ) 35 radius = value; 36 } 37 } 38 39 // calculate Circle2 diameter 40 public double Diameter() 41 { 42 return Radius * 2; 43 } 44 45 // calculate Circle2 circumference 46 public double Circumference() 47 { 48 return Math.PI * Diameter(); 49 } 50 51 // calculate Circle2 area 52 public override double Area() 53 { 54 return Math.PI * Math.Pow( Radius, 2 ); 55 } 56 57 // return string representation of Circle2 object 58 public override string ToString() 59 { 60 return "Center = " + base.ToString() + 61 "; Radius = " + Radius; 62 } Circle2.cs Override the Area method (defined in class Shape)

Override the read-only Name property 63 64 // override property Name from class Point2 65 public override string Name 66 { 67 get 68 { 69 return "Circle2"; 70 } 71 } 72 73 } // end class Circle2 Override the read-only Name property Circle2.cs

Class Cylinder2 derives from Circle2 1 // Fig. 10.7 ed1: Cylinder2.cs 2 // Cylinder2 inherits from class Circle2 and overrides key members. 3 using System; 4 5 // Cylinder2 inherits from class Circle2 6 public class Cylinder2 : Circle2 7 { 8 private double height; // Cylinder2 height 9 10 // default constructor 11 public Cylinder2() 12 { 13 // implicit call to Circle2 constructor occurs here 14 } 15 16 // constructor 17 public Cylinder2( int xValue, int yValue, double radiusValue, 18 double heightValue ) : base( xValue, yValue, radiusValue ) 19 { 20 Height = heightValue; 21 } 22 23 // property Height 24 public double Height 25 { 26 get 27 { 28 return height; 29 } 30 31 set 32 { 33 // ensure non-negative height value 34 if ( value >= 0 ) 35 height = value; Cylinder2.cs Class Cylinder2 derives from Circle2

Override Area implementation of class Circle2 Cylinder2.cs 36 } 37 } 38 39 // calculate Cylinder2 area 40 public override double Area() 41 { 42 return 2 * base.Area() + base.Circumference() * Height; 43 } 44 45 // calculate Cylinder2 volume 46 public override double Volume() 47 { 48 return base.Area() * Height; 49 } 50 51 // return string representation of Circle2 object 52 public override string ToString() 53 { 54 return base.ToString() + "; Height = " + Height; 55 } 56 57 // override property Name from class Circle2 58 public override string Name 59 { 60 get 61 { 62 return "Cylinder2"; 63 } 64 } 65 66 } // end class Cylinder2 Override Area implementation of class Circle2 Cylinder2.cs Override Volume implementation of class Shape Override read-only property Name

Create an array of Shape objects 1 // Fig. 10.8 ed1: AbstractShapesTest.cs 2 // Demonstrates polymorphism in Point-Circle-Cylinder hierarchy. 3 using System; 4 using System.Windows.Forms; 5 6 public class AbstractShapesTest 7 { 8 public static void Main( string[] args ) 9 { 10 // instantiate Point2, Circle2 and Cylinder2 objects 11 Point2 point = new Point2( 7, 11 ); 12 Circle2 circle = new Circle2( 22, 8, 3.5 ); 13 Cylinder2 cylinder = new Cylinder2( 10, 10, 3.3, 10 ); 14 15 // create empty array of Shape base-class references 16 Shape[] arrayOfShapes = new Shape[ 3 ]; 17 18 // arrayOfShapes[ 0 ] refers to Point2 object 19 arrayOfShapes[ 0 ] = point; //assign instance of derived class 20 21 // arrayOfShapes[ 1 ] refers to Circle2 object 22 arrayOfShapes[ 1 ] = circle; 23 24 // arrayOfShapes[ 1 ] refers to Cylinder2 object 25 arrayOfShapes[ 2 ] = cylinder; 26 27 string output = point.Name + ": " + point + "\n" + 28 circle.Name + ": " + circle + "\n" + 29 cylinder.Name + ": " + cylinder; 30 AbstractShapesTest.cs Create an array of Shape objects Assign a Shape reference to reference a Point2 object Assign a Shape reference to reference a Circle2 object Assign a Shape reference to reference a Cylinder2 object

AbstractShapesTest.cs Program Output 31 // display Name, Area and Volume for each object 32 // in arrayOfShapes polymorphically 33 foreach( Shape shape in arrayOfShapes ) 34 { 35 output += "\n\n" + shape.Name + ": " + shape + 36 "\nArea = " + shape.Area().ToString( "F" ) + 37 "\nVolume = " + shape.Volume().ToString( "F" ); 38 } 39 40 MessageBox.Show( output, "Demonstrating Polymorphism" ); 41 } 42 } Use a foreach loop to access every element of the array AbstractShapesTest.cs Program Output To verify all previous outputs: Rely on polymorphism to call the proper object’s methods (i.e. it maps each methods call to the proper object method)

Case Study: Inheriting Interface and Implementation Dynamic binding (late binding) Accommodates new classes Object’s type need not be known at compile time At run time, method call matched with object Create an array of Shape references Point to various derived class objects Call methods using Shape reference

12.5 Case Study: Payroll System Using Polymorphism Base-class Employee abstract abstract method Earnings Classes that derive from Employee Boss CommissionWorker PieceWorker HourlyWorker All derived-classes implement method Earnings Driver program uses Employee references to refer to instances of derived-classes Polymorphism calls the correct version of Earnings

12.5 Case Study: Payroll System Using Polymorphism Create a payroll program Use abstract methods and polymorphism Problem statement 4 types of employees, paid weekly Salaried (fixed salary, no matter the hours) Hourly (overtime [>40 hours] pays time and a half) Commission (paid percentage of sales) Base-plus-commission (base salary + percentage of sales) Boss wants to raise pay by 10% abstract base-class Employee has abstract method earnings Method earnings must be implemented in each employee’s subclasses Person’s earnings dependent on type of Employee Class EmployeeTest Initialize objects Use an Employee reference and call toString and earnings Through polymorphism, appropriate class method called

Definition of abstract class Employee 1 // Fig. 10.9 ed1: Employee.cs 2 // Abstract base class for company employees. 3 using System; 4 5 public abstract class Employee 6 { 7 private string firstName; 8 private string lastName; 9 10 // constructor 11 public Employee( string firstNameValue, 12 string lastNameValue ) 13 { 14 FirstName = firstNameValue; 15 LastName = lastNameValue; 16 } 17 18 // property FirstName 19 public string FirstName 20 { 21 get 22 { 23 return firstName; 24 } 25 26 set 27 { 28 firstName = value; 29 } 30 } 31 Employee.cs Definition of abstract class Employee

32 // property LastName 33 public string LastName 34 { 35 get 36 { 37 return lastName; 38 } 39 40 set 41 { 42 lastName = value; 43 } 44 } 45 46 // return string representation of Employee 47 public override string ToString() 48 { 49 return FirstName + " " + LastName; 50 } 51 52 // abstract method that must be implemented for each derived 53 // class of Employee to calculate specific earnings 54 public abstract decimal Earnings(); 55 56 } // end class Employee Employee.cs Declaration of abstract class Earnings – implementation must be provided by all derived classes

Definition of class Boss – derives from Employee Boss.cs 1 // Fig. 10.10 ed1: Boss.cs 2 // Boss class derived from Employee. 3 using System; 4 5 public class Boss : Employee 6 { 7 private decimal salary; // Boss's salary 8 9 // constructor 10 public Boss( string firstNameValue, string lastNameValue, 11 decimal salaryValue) 12 : base( firstNameValue, lastNameValue ) 13 { 14 WeeklySalary = salaryValue; 15 } 16 17 // property WeeklySalary 18 public decimal WeeklySalary 19 { 20 get 21 { 22 return salary; 23 } 24 25 set 26 { 27 // ensure positive salary value 28 if ( value > 0 ) 29 salary = value; 30 } 31 } 32 Definition of class Boss – derives from Employee Boss.cs

33 // override base-class method to calculate Boss's earnings 34 public override decimal Earnings() 35 { 36 return WeeklySalary; 37 } 38 39 // return string representation of Boss 40 public override string ToString() 41 { 42 return "Boss: " + base.ToString(); 43 } 44 } Implementation of method Earnings (required by classes deriving from Employee) Boss.cs

Definition of class CommissionWorker – derives from Employee 1 // Fig. 10.11 ed1: CommisionWorker.cs 2 // CommissionWorker class derived from Employee 3 using System; 4 5 public class CommissionWorker : Employee 6 { 7 private decimal salary; // base weekly salary 8 private decimal commission; // amount paid per item sold 9 private int quantity; // total items sold 10 11 // constructor 12 public CommissionWorker( string firstNameValue, 13 string lastNameValue, decimal salaryValue, 14 decimal commissionValue, int quantityValue ) 15 : base( firstNameValue, lastNameValue ) 16 { 17 WeeklySalary = salaryValue; 18 Commission = commissionValue; 19 Quantity = quantityValue; 20 } 21 22 // property WeeklySalary 23 public decimal WeeklySalary 24 { 25 get 26 { 27 return salary; 28 } 29 Definition of class CommissionWorker – derives from Employee CommisionWorker.cs

CommisionWorker.cs 30 set 31 { 32 // ensure non-negative salary value 31 { 32 // ensure non-negative salary value 33 if ( value > 0 ) 34 salary = value; 35 } 36 } 37 38 // property Commission 39 public decimal Commission 40 { 41 get 42 { 43 return commission; 44 } 45 46 set 47 { 48 // ensure non-negative commission value 49 if ( value > 0 ) 50 commission = value; 51 } 52 } 53 54 // property Quantity 55 public int Quantity 56 { 57 get 58 { 59 return quantity; 60 } 61 CommisionWorker.cs

62 set 63 { 64 // ensure non-negative quantity value 65 if ( value > 0 ) 66 quantity = value; 67 } 68 } 69 70 // override base-class method to calculate 71 // CommissionWorker's earnings 72 public override decimal Earnings() 73 { 74 return WeeklySalary + Commission * Quantity; 75 } 76 77 // return string representation of CommissionWorker 78 public override string ToString() 79 { 80 return "CommissionWorker: " + base.ToString(); 81 } 82 83 } // end class CommissionWorker CommisionWorker.cs Implementation of method Earnings (required by classes deriving from Employee)

Definition of class PieceWorker – derives from Employee PieceWorker.cs 1 // Fig. 10.12 ed1: PieceWorker.cs 2 // PieceWorker class derived from Employee. 3 using System; 4 5 public class PieceWorker : Employee 6 { 7 private decimal wagePerPiece; // wage per piece produced 8 private int quantity; // quantity of pieces produced 9 10 // constructor 11 public PieceWorker( string firstNameValue, 12 string lastNameValue, decimal wagePerPieceValue, 13 int quantityValue ) 14 : base( firstNameValue, lastNameValue ) 15 { 16 WagePerPiece = wagePerPieceValue; 17 Quantity = quantityValue; 18 } 19 20 // property WagePerPiece 21 public decimal WagePerPiece 22 { 23 get 24 { 25 return wagePerPiece; 26 } 27 28 set 29 { 30 if ( value > 0 ) 31 wagePerPiece = value; 32 } 33 } 34 Definition of class PieceWorker – derives from Employee PieceWorker.cs

35 // property Quantity 36 public int Quantity 37 { 38 get 39 { 40 return quantity; 41 } 42 43 set 44 { 45 if ( value > 0 ) 46 quantity = value; 47 } 48 } 49 50 // override base-class method to calculate 51 // PieceWorker's earnings 52 public override decimal Earnings() 53 { 54 return Quantity * WagePerPiece; 55 } 56 57 // return string representation of PieceWorker 58 public override string ToString() 59 { 60 return "PieceWorker: " + base.ToString(); 61 } 62 } PieceWorker.cs Implementation of method Earnings (required by classes deriving from Employee)

Definition of class HourlyWorker – derives from Employee 1 // Fig. 10.13 ed1: HourlyWorker.cs 2 // HourlyWorker class derived from Employee. 3 using System; 4 5 public class HourlyWorker : Employee 6 { 7 private decimal wage; // wage per hour of work 8 private double hoursWorked; // hours worked during week 9 10 // constructor 11 public HourlyWorker( string firstNameValue, string LastNameValue, 12 decimal wageValue, double hoursWorkedValue ) 13 : base( firstNameValue, LastNameValue ) 14 { 15 Wage = wageValue; 16 HoursWorked = hoursWorkedValue; 17 } 18 19 // property Wage 20 public decimal Wage 21 { 22 get 23 { 24 return wage; 25 } 26 27 set 28 { 29 // ensure non-negative wage value 30 if ( value > 0 ) 31 wage = value; 32 } 33 } 34 Definition of class HourlyWorker – derives from Employee HourlyWorker.cs

35 // property HoursWorked 36 public double HoursWorked 37 { 38 get 39 { 40 return hoursWorked; 41 } 42 43 set 44 { 45 // ensure non-negative hoursWorked value 46 if ( value > 0 ) 47 hoursWorked = value; 48 } 49 } 50 51 // override base-class method to calculate 52 // HourlyWorker earnings 53 public override decimal Earnings() 54 { 55 // compensate for overtime (paid "time-and-a-half") 56 if ( HoursWorked <= 40 ) 57 { 58 return Wage * Convert.ToDecimal( HoursWorked ); 59 } 60 61 else 62 { 63 // calculate base and overtime pay 64 decimal basePay = Wage * Convert.ToDecimal( 40 ); 65 decimal overtimePay = Wage * 1.5M * 66 Convert.ToDecimal( HoursWorked - 40 ); 67 HourlyWorker.cs Implementation of method Earnings (required by classes deriving from Employee)

HourlyWorker.cs 68 return basePay + overtimePay; 69 } 70 } 71 69 } 70 } 71 72 // return string representation of HourlyWorker 73 public override string ToString() 74 { 75 return "HourlyWorker: " + base.ToString(); 76 } 77 } HourlyWorker.cs

Assign Employee reference to reference a Boss object 1 // Fig. 10.14 ed1: EmployeesTest.cs 2 // Demonstrates polymorphism by displaying earnings 3 // for various Employee types. 4 using System; 5 using System.Windows.Forms; 6 7 public class EmployeesTest 8 { 9 public static void Main( string[] args ) 10 { 11 Boss boss = new Boss( "John", "Smith", 800 ); 12 13 CommissionWorker commissionWorker = 14 new CommissionWorker( "Sue", "Jones", 400, 3, 150 ); 15 16 PieceWorker pieceWorker = new PieceWorker( "Bob", "Lewis", 17 Convert.ToDecimal( 2.5 ), 200 ); 18 19 HourlyWorker hourlyWorker = new HourlyWorker( "Karen", 20 "Price", Convert.ToDecimal( 13.75 ), 50 ); 21 22 Employee employee = boss; 23 24 string output = GetString( employee ) + boss + " earned " + 25 boss.Earnings().ToString( "C" ) + "\n\n"; // it gives 2 the same output lines 26 // "C“ = currency 27 employee = commissionWorker; 28 29 output += GetString( employee ) + commissionWorker + 30 " earned " + 31 commissionWorker.Earnings().ToString( "C" ) + "\n\n"; 32 33 employee = pieceWorker; 34 EmployeesTest.cs Use method GetString() (below see local call) to polymorphically obtain salary information. Then use the original Boss reference to obtain the information Assign Employee reference to reference a Boss object

EmployeesTest.cs Program Output 35 output += GetString( employee ) + pieceWorker + 36 " earned " + pieceWorker.Earnings().ToString( "C" ) + 37 "\n\n"; 38 39 employee = hourlyWorker; 40 41 output += GetString( employee ) + hourlyWorker + 42 " earned " + hourlyWorker.Earnings().ToString( "C" ) + 43 "\n\n"; 44 45 MessageBox.Show( output, "Demonstrating Polymorphism", 46 MessageBoxButtons.OK, MessageBoxIcon.Information ); 47 48 } // end method Main 49 50 // return string that contains Employee information 51 public static string GetString( Employee worker ) 52 { 53 return worker.ToString() + " earned " + // polymorphic call 54 worker.Earnings().ToString( "C" ) + "\n"; // ToString( "C" ) converts from //decimal earnings into a currency amount 55 } 56 } EmployeesTest.cs Program Output Definition of method GetString, which takes as an argument an Employee object and gives the 1st line output for each of 4 workers. To verify all previous outputs Polymorphically call the method ToString() and Earnings() of the appropriate derived class Output: The 1st line in each group shows that the polymorphic methods invoke the appropriate methods in derived objects

Fig. 12.2 | Employee hierarchy UML class diagram - last 5th edition = Employee (ed4) = Boss (ed4) = HourlyWorker (ed4) <= 2nd level = CommissionWorker (ed4) Compare with the previous example: SalariedEmployee = Boss (ed4) BasePlusCommissionEmployee = CommissionWorker (ed4) HourlyEmployee = HourlyWorker (ed4)

Fig. 12.3 | Polymorphic interface for the Employee hierarchy classes. = Boss(ed4) = HourlyWorker (ed4) = CommissionWorker (ed4) = Boss (ed4) = HourlyWorker (ed4) = CommissionWorker (ed4)

Outline Employee.cs (1 of 2)

Outline Employee.cs (2 of 2)

Outline SalariedEmployee.cs (1 of 2)

Outline SalariedEmployee .cs (2 of 2)

Outline HourlyEmployee.cs (1 of 3)

Outline HourlyEmployee.cs (2 of 3)

Outline HourlyEmployee.cs (3 of 3)

Outline CommissionEmployee.cs (1 of 2)

Outline CommissionEmployee.cs (2 of 2)

Outline BasePlusCommissionEmployee.cs (1 of 2)

Outline BasePlusCommissionEmployee.cs (2 of 2)

PayrollSystemTest.cs (1 of 5) Outline

Outline PayrollSystemTest.cs (2 of 5)

Outline PayrollSystemTest.cs (3 of 5)