 2002 Prentice Hall. All rights reserved. 1 Introduction Polymorphism allows programmers to write: –Programs that handle a wide variety of related classes.

Slides:



Advertisements
Similar presentations
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - Object-Oriented Programming: Polymorphism Outline 10.1 Introduction 10.2 Relationships Among.
Advertisements

OOP: Inheritance By: Lamiaa Said.
 2002 Prentice Hall. All rights reserved. 1 Chapter 9 – Object-Oriented Programming: Inheritance Outline 9.1Introduction 9.2Base Classes and Derived Classes.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
 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 Inheritance and Polymorphism Professor Evan Korth New York University.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
2 Objectives You should be able to describe: Operator Functions Two Useful Alternatives – operator() and operator[] Data Type Conversions Class Inheritance.
Polymorphism. Lecture Objectives To understand the concept of polymorphism To understand the concept of static or early binding To understand the concept.
 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.
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
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
CISC6795: Spring Object-Oriented Programming: Polymorphism.
Lecture 9 Polymorphism Richard Gesick.
Advanced Programming Collage of Information Technology University of Palestine, Gaza Prepared by: Mahmoud Rafeek Alfarra Lecture 1: Course overview.
1 Object-Oriented Programming: Polymorphism 10.1 Introduction 10.2 Relationships Among Objects in an Inheritance Hierarchy Invoking Superclass Methods.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
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.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
Object-Oriented Programming Polymorphism Session 07 Mata kuliah: M0874 – Programming II Tahun: 2010.
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
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.
Inheritance & Polymorphism1. 2 Introduction Besides composition, another form of reuse is inheritance. With inheritance, an object can inherit behavior.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 9 - Inheritance Outline 9.1Introduction 9.2Inheritance: Base Classes and Derived Classes 9.3.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 9 - Object-Oriented Programming: Inheritance Outline 9.1 Introduction 9.2 Superclasses and Subclasses.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Object Oriented Programming
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
 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 Passing Methods as Arguments public void BubbleSortArray( int[] array, Comparator Compare ) { for ( int pass.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
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.
Jozef Goetz contribution,  2011 Pearson Education, Inc. All rights reserved.  2002 Prentice Hall. All rights reserved.
 2002 Prentice Hall. All rights reserved. 1 Chapter 11 – [Object-Oriented Programming] Polymorphism, Interfaces & Operator Overloading Section [order.
Jozef Goetz contribution,  2011, 2014 Pearson Education, Inc. All rights reserved.  2002 Prentice Hall. All rights reserved.
Object-Oriented Programming: Inheritance and Polymorphism.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 20 - Virtual Functions Outline 20.1Introduction 20.2Type Fields and switch Statements 20.3Virtual.
Object-Oriented Programming: Polymorphism Chapter 10.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 9 - Object-Oriented Programming: Inheritance Outline 9.1 Introduction 9.2 Base Classes and Derived.
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.
Polymorphism & Virtual Functions 1. Objectives 2  Polymorphism in C++  Pointers to derived classes  Important point on inheritance  Introduction to.
C++ How to Program, 7/e. © by Pearson Education, Inc. All Rights Reserved.2.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Chapters 9, 10 – Object-Oriented Programming: Inheritance
Questions from last lesson
Chapter 9 – Object-Oriented Programming: Inheritance
 2002 Prentice Hall. All rights reserved.
Polymorphism & Virtual Functions
IST311 Advanced Issues in OOP: Inheritance and Polymorphism
Lecture 23 Polymorphism Richard Gesick.
Week 6 Object-Oriented Programming (2): Polymorphism
Polymorphism, Interfaces &
Polymorphism and Type Casting
Fundaments of Game Design
CIS 199 Final Review.
Presentation transcript:

 2002 Prentice Hall. All rights reserved. 1 Introduction Polymorphism allows programmers to write: –Programs that handle a wide variety of related classes in a generic manner –Systems that are easily extensible and maintainable

 2002 Prentice Hall. All rights reserved. 2 Derived-Class-Object to Base-Class-Object Conversion Class hierarchies –Can assign derived-class objects to base-class references –Can explicitly cast between types in a class hierarchy An object of a derived-class can be treated as an object of its base-class –Array of base-class references that refer to objects of many derived-class types –Base-class object is NOT an object of any of its derived classes

 2002 Prentice Hall. All rights reserved. Outline 3 13 Point point1 = new Point( 30, 50 ); 14 Circle circle1 = new Circle( 120, 89, 2.7 ); string output = "Point point1: " + point1.ToString() + 17 "\nCircle circle1: " + circle1.ToString(); // use 'is a' relationship to assign 20 // Circle circle1 to Point reference 21 Point point2 = circle1; output += "\n\nCCircle circle1 (via point2): " + 24 point2.ToString(); // downcast (cast base-class reference to derived-class 27 // data object type) point2 to Circle circle2 28 Circle circle2 = ( Circle ) point2; output += "\n\nCircle circle1 (via circle2): " + 31 circle2.ToString(); output += "\nArea of circle1 (via circle2): " + 34 circle2.Area().ToString( "F" ); 35 Create a Point object Create a Circle object Assign a Point reference to reference a Circle object Assign a Circle reference to reference a Point object (downcast) Use base-class reference to access a derived-class object Use derived-class reference to access a base-class object

 2002 Prentice Hall. All rights reserved. Outline 4 36 // attempt to assign point1 object to Circle reference 37 if ( point1 is Circle ) 38 { 39 circle2 = ( Circle ) point1; 40 output += "\n\ncast successful"; 41 } 42 else 43 { 44 output += "\n\npoint1 does not refer to a Circle"; 45 } MessageBox.Show( output, "Demonstrating the 'is a' relationship" ); Test if point1 references a Circle object – it cannot, because of the downcasting on line 28

 2002 Prentice Hall. All rights reserved. 5 Comments With virtual method, such as ToString – the version called depends on type of object, not type of reference. Assigning a base-class object (or a base-class reference) to a derived-class reference (without and explicit cast) is a syntax error. If an invalid cast is attempted, C# throws an InvalidCastException The is keyword enables a program to determine whether a cast operation would be successful.

 2002 Prentice Hall. All rights reserved. 6 Types and switch Statements Using switch to determine the type of an object –Distinguish between object, perform appropriate action depending on object type Potential problems using switch –Forgetting to include a type test or testing all possible cases –Forgetting to modify all relevant switch structures, when new types are added –Every addition or deletion of a class requires modification of every switch statement in the system; C#’s polymorphic mechanism performs the equivalent logic, eliminating unnecessary switch logic.

 2002 Prentice Hall. All rights reserved. 7 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

 2002 Prentice Hall. All rights reserved. 8 Abstract Classes and Methods Abstract classes –Cannot be instantiated –Used as base classes –Class definitions are not complete – derived classes must define the missing pieces –Can contain abstract methods and/or abstract properties Have no implementation Derived classes must override inherited abstract methods and properties to enable instantiation

 2002 Prentice Hall. All rights reserved. 9 Abstract Classes and Methods Abstract classes are used to provide appropriate base classes from which other (concrete) classes may inherit Abstract base classes are too generic to define real objects To define an abstract class, use keyword abstract in the declaration To declare a method or property abstract, use keyword abstract in the declaration; abstract methods and properties have no implementation

 2002 Prentice Hall. All rights reserved. 10 Abstract Classes and Methods Any class with an abstract method or property must be declared abstract Concrete classes use the keyword override to provide implementations for all the abstract methods and properties of the base-class 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

 2002 Prentice Hall. All rights reserved. 11 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 property Name –Overrides methods Area and Volume

 2002 Prentice Hall. All rights reserved. Outline 12 5 public abstract class Shape 6 { 7 // return Shape's area 8 public virtual double Area() 9 { 10 return 0; 11 } // return Shape's volume 14 public virtual double Volume() 15 { 16 return 0; 17 } // return Shape's name 20 public abstract string Name 21 { 22 get; 23 } 24 } 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

 2002 Prentice Hall. All rights reserved. Outline 13 Point2.cs 6 // Point2 inherits from abstract class Shape 7 public class Point2 : Shape 8 { 9 private int x, y; // Point2 coordinates 58 // implement abstract property Name of class Shape 59 public override string Name 60 { 61 get 62 { 63 return "Point2"; 64 } 65 } Class Point2 inherits from class Shape Point2’s implementation of the read-only Name property

 2002 Prentice Hall. All rights reserved. Outline 14 5 // Circle2 inherits from class Point2 6 public class Circle2 : Point2 7 { 8 private double radius; // Circle2 radius 9 51 // calculate Circle2 area 52 public override double Area() 53 { 54 return Math.PI * Math.Pow( Radius, 2 ); 55 } 64 // override property Name from class Point2 65 public override string Name 66 { 67 get 68 { 69 return "Circle2"; 70 } 71 } Definition of class Circle2 which inherits from class Point2 Override the Area method (defined in class Shape) Override the read-only Name property

 2002 Prentice Hall. All rights reserved. Outline 15 Cylinder2.cs 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 } // constructor 17 public Cylinder2( int xValue, int yValue, double radiusValue, 18 double heightValue ) : base( xValue, yValue, radiusValue ) 19 { 20 Height = heightValue; 21 } // property Height 24 public double Height 25 { 26 get 27 { 28 return height; 29 } 31 set 32 { // ensure non-negative height value 34 if ( value >= 0 ) 35 height = value; 36 } 37 } Class Cylinder2 derives from Circle2

 2002 Prentice Hall. All rights reserved. Outline 16 Cylinder2.cs 39 // calculate Cylinder2 area 40 public override double Area() 41 { 42 return 2 * base.Area() + base.Circumference() * Height; 43 } // calculate Cylinder2 volume 46 public override double Volume() 47 { 48 return base.Area() * Height; 49 } // return string representation of Circle2 object 52 public override string ToString() 53 { 54 return base.ToString() + "; Height = " + Height; 55 } // override property Name from class Circle2 58 public override string Name 59 { 60 get 61 { 62 return "Cylinder2"; 63 } 64 } } // end class Cylinder2 Override Area implementation of class Circle2 Override read-only property Name Override Volume implementation of class Shape

 2002 Prentice Hall. All rights reserved. Outline 17 2 // Demonstrates polymorphism in Point-Circle-Cylinder hierarchy. 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 ); // create empty array of Shape base-class references 16 Shape[] arrayOfShapes = new Shape[ 3 ]; // arrayOfShapes[ 0 ] refers to Point2 object 19 arrayOfShapes[ 0 ] = point; // arrayOfShapes[ 1 ] refers to Circle2 object 22 arrayOfShapes[ 1 ] = circle; // arrayOfShapes[ 1 ] refers to Cylinder2 object 25 arrayOfShapes[ 2 ] = cylinder; string output = point.Name + ": " + point + "\n" + 28 circle.Name + ": " + circle + "\n" + 29 cylinder.Name + ": " + cylinder; 30 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

 2002 Prentice Hall. All rights reserved. Outline // 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 } MessageBox.Show( output, "Demonstrating Polymorphism" ); 41 } 42 } Use a foreach loop to access every element of the array Rely on polymorphism to call appropriate version of methods

 2002 Prentice Hall. All rights reserved. 19 sealed Classes and Methods sealed is a keyword in C# sealed methods cannot be overridden in a derived class –Methods that are declared static and private, are implicitly sealed sealed classes cannot have any derived-classes Creating sealed classes can allow some runtime optimizations –e.g., virtual method calls can be transformed into non- virtual method calls

 2002 Prentice Hall. All rights reserved. 20 Case Study: Creating and Using Interfaces Interfaces specify the public services (methods and properties) that classes must implement Interfaces provide no default implementations (i.e., no instance variables and no default- method implementations) vs. abstract classes which may provide some default implementations Interfaces are used to “bring together” or relate disparate objects that relate to one another only through the interface

 2002 Prentice Hall. All rights reserved. 21 Case Study: Creating and Using Interfaces Interfaces are defined using keyword interface Use inheritance notation to specify a class implements an interface (ClassName : InterfaceName) Classes may implement more then one interface (a comma separated list of interfaces) Classes that implement an interface must provide implementations for every method and property in the interface definition Example: interface IShape that specifies methods Area and Volume and property Name. Example: interface IAge that returns information about an object’s age –Can be used by classes for people, cars, trees (all have an age)

 2002 Prentice Hall. All rights reserved. Outline 22 // Interface IAge declares property for setting and getting age. public interface IAge { int Age { get; } string Name { get; } } Definition of interface IAge Classes implementing this interface will have to define read- only properties Age and Name

 2002 Prentice Hall. All rights reserved. Outline 23 5 public class Person : IAge 6 { 7 private string firstName; 8 private string lastName; 9 private int yearBorn; // constructor 12 public Person( string firstNameValue, string lastNameValue, 13 int yearBornValue ) 14 { 15 firstName = firstNameValue; 16 lastName = lastNameValue; if ( yearBornValue > 0 && yearBornValue <= DateTime.Now.Year ) 19 yearBorn = yearBornValue; 20 else 21 yearBorn = DateTime.Now.Year; 22 } // property Age implementation of interface IAge 25 public int Age 26 { 27 get 28 { 29 return DateTime.Now.Year - yearBorn; 30 } 31 } 32 Class Person implements the IAge interface Definition of Age property (required)

 2002 Prentice Hall. All rights reserved. Outline 24 // property Name implementation of interface IAge public string Name { get { return firstName + " " + lastName; } Definition of Name property (required)

 2002 Prentice Hall. All rights reserved. Outline 25 2 // Class Tree contains number of rings corresponding to its age. 5 public class Tree : IAge 6 { 7 private int rings; // number of rings in tree trunk 8 9 // constructor 10 public Tree( int yearPlanted ) 11 { 12 // count number of rings in Tree 13 rings = DateTime.Now.Year - yearPlanted; 14 } // increment rings 17 public void AddRing() 18 { 19 rings++; 20 } // property Age implementation of interface IAge 23 public int Age 24 { 25 get 26 { 27 return rings; 28 } 29 } Class Tree implements the IAge interface Implementation of Age property ( required)

 2002 Prentice Hall. All rights reserved. Outline 26 Tree.cs // property Name implementation of interface IAge 32 public string Name 33 { 34 get 35 { 36 return "Tree"; 37 } 38 } } // end class Tree Definition of Name property (required)

 2002 Prentice Hall. All rights reserved. Outline 27 InterfacesTest.c s 5 public class InterfacesTest 6 { 7 public static void Main( string[] args ) 8 { 9 Tree tree = new Tree( 1978 ); 10 Person person = new Person( "Bob", "Jones", 1971 ); // create array of IAge references 13 IAge[] iAgeArray = new IAge[ 2 ]; // iAgeArray[ 0 ] refers to Tree object polymorphically 16 iAgeArray[ 0 ] = tree; // iAgeArray[ 1 ] refers to Person object polymorphically 19 iAgeArray[ 1 ] = person; // display tree information 22 string output = tree + ": " + tree.Name + "\nAge is " + 23 tree.Age + "\n\n"; // display person information 26 output += person + ": " + person.Name + "\nAge is: " 27 + person.Age + "\n\n"; 28 Create array of IAge references Assign an IAge reference to reference a Tree object Assign an IAge reference to reference a Person object

 2002 Prentice Hall. All rights reserved. Outline // display name and age for each IAge object in iAgeArray 30 foreach ( IAge ageReference in iAgeArray ) 31 { 32 output += ageReference.Name + ": Age is " + 33 ageReference.Age + "\n"; 34 } MessageBox.Show( output, "Demonstrating Polymorphism" ); } // end method Main } // end class InterfacesTest Use foreach loop to access each element of the array Use polymorphism to call the property of the appropriate class

 2002 Prentice Hall. All rights reserved. 29 Delegates Sometimes useful to pass methods as arguments to other methods C# does not allow passing of method references directly as arguments, but does provide delegates Delegates are sets of references to methods Delegate objects can be passed to methods; methods can then invoke the methods the delegate objects refer to Delegates that contain one method are known as singlecast delegates and are created or derived from class Delegate Delegates that contain multiple methods are known as multicast delegates and are created or derived from class MulticastDelegate

 2002 Prentice Hall. All rights reserved. 30 Delegates Delegates must be declared before use A delegate declaration specifies the parameters and return type of the methods the delegate can refer to Methods that can be referred to by a delegate, must have the same signature as the delegate Delegate instances can then be created to refer to a method(s) Once a delegate instance is created, the method it refers to can be invoked

 2002 Prentice Hall. All rights reserved. Outline 31 1 // DelegateBubbleSort.cs 2 // Demonstrating delegates for sorting numbers. 3 4 public class DelegateBubbleSort 5 { 6 public delegate bool Comparator( int element1, 7 int element2 ); 8 9 // sort array using Comparator delegate 10 public static void SortArray( int[] array, 11 Comparator Compare ) 12 { 13 for ( int pass = 0; pass < array.Length; pass++ ) for ( int i = 0; i < array.Length - 1; i++ ) if ( Compare( array[ i ], array [ i + 1 ] ) ) 18 Swap( ref array[ i ], ref array[ i + 1 ] ); 19 } // swap two elements 22 private static void Swap( ref int firstElement, 23 ref int secondElement ) 24 { 25 int hold = firstElement; 26 firstElement = secondElement; 27 secondElement = hold; 28 } 29 } Delegate Comparator definition declaration; defines a delegate to a method that takes two integer parameters and returns a boolean Method SortArray which takes an integer array and a Comparator delegate Call delegate method to compare array elements Method Swap, swaps the two arguments (passed by reference)

 2002 Prentice Hall. All rights reserved. Outline 32 2 // Demonstrates bubble sort using delegates to determine 3 // the sort order. 10 public class BubbleSortForm : System.Windows.Forms.Form 11 { 20 private int[] elementArray = new int[ 10 ]; // create randomly generated set of numbers to sort 23 private void createButton_Click( object sender, 24 System.EventArgs e ) 25 { ….. 39 } 41 // delegate implementation for ascending sort 42 private bool SortAscending ( int element1, int element2 ) 43 { 44 return element1 > element2; 45 } // sort randomly generated numbers in ascending order 48 private void ascendingButton_Click( object sender, 49 System.EventArgs e ) 50 { 51 // sort array, passing delegate for SortAscending 52 DelegateBubbleSort.SortArray( elementArray, 53 new DelegateBubbleSort.Comparator( 54 SortAscending ) ); DisplayResults(); 57 } // delegate implementation for descending sort 60 private bool SortDescending ( int element1, int element2 ) 61 { 62 return element1 < element2; 63 } Method SortAscending returns true if the first argument is larger then the second; returns false otherwise Method SortDescending returns true if the first argument is smaller then the second; returns false otherwise To sort in ascending order, send a delegate for the SortAscending method to method SortArray

 2002 Prentice Hall. All rights reserved. Outline // sort randomly generating numbers in descending order 66 private void descendingButton_Click ( object sender, 67 System.EventArgs e ) 68 { 69 // sort array, passing delegate for SortDescending 70 DelegateBubbleSort.SortArray( elementArray, 71 new DelegateBubbleSort.Comparator( 72 SortDescending ) ); DisplayResults(); 75 } // display the sorted array in sortedTextBox 78 private void DisplayResults() 79 {….. 91 } To sort in descending order, send a delegate to the SortDescending method to method SortArray

 2002 Prentice Hall. All rights reserved. Outline 34

 2002 Prentice Hall. All rights reserved. 35 Operator Overloading C# contains many operators (such as + and - ) that are defined for some primitive types It is often useful to use operators with user-defined types (e.g., a complex number class) Operator notation may often be more intuitive then method calls As in C++, C# allows programmers to overload operators to make them sensitive to the context in which they are used

 2002 Prentice Hall. All rights reserved. 36 Operator Overloading Methods define the actions to be taken for the overloaded operator They are in the form: public static ReturnType operator operator-to-be-overloaded( arguments ) –These methods must be declared public and static –The return type is the type returned as the result of evaluating the operation –The keyword operator follows the return type to specify that this method defines an operator overload –The last piece of information is the operator to be overloaded (such as +, -, *, etc.) –If the operator is unary, one argument must be specified, if the operator is binary, then two, etc.

 2002 Prentice Hall. All rights reserved. Outline 37 public class ComplexNumber { private int real; private int imaginary; // overload the addition operator public static ComplexNumber operator + ( ComplexNumber x, ComplexNumber y ) { return new ComplexNumber( x.Real + y.Real, x.Imaginary + y.Imaginary ); } // provide alternative to overloaded + operator for addition public static ComplexNumber Add( ComplexNumber x, ComplexNumber y ) { return x + y; } Class ComplexNumber definition Overload the addition (+) operator for ComplexNumbers. Method Add – provides an alternative to the addition operator

 2002 Prentice Hall. All rights reserved. Outline 38 ComplexNumber.cs 74 // overload the subtraction operator 75 public static ComplexNumber operator - ( 76 ComplexNumber x, ComplexNumber y ) 77 { 78 return new ComplexNumber( 79 x.Real - y.Real, x.Imaginary - y.Imaginary ); 80 } // provide alternative to overloaded - operator 83 // for subtraction 84 public static ComplexNumber Subtract( ComplexNumber x, 85 ComplexNumber y ) 86 { 87 return x - y; 88 } // overload the multiplication operator 91 public static ComplexNumber operator * ( 92 ComplexNumber x, ComplexNumber y ) 93 { 94 return new ComplexNumber( 95 x.Real * y.Real - x.Imaginary * y.Imaginary, 96 x.Real * y.Imaginary + y.Real * x.Imaginary ); 97 } 99 // provide alternative to overloaded * operator 100 // for multiplication 101 public static ComplexNumber Multiply( ComplexNumber x, 102 ComplexNumber y ) 103 { 104 return x * y; 105 } Overload the subtraction (-) operator for ComplexNumbers Method Subtract – provides an alternative to the subtraction operator Overloads the multiplication (*) operator for ComplexNumbers

 2002 Prentice Hall. All rights reserved. Outline public class ComplexTest : System.Windows.Forms.Form 12 { 26 private ComplexNumber x = new ComplexNumber(); 27 private ComplexNumber y = new ComplexNumber(); 55 // add complex numbers 56 private void addButton_Click( object sender, System.EventArgs e ) 57 { 58 statusLabel.Text = x + " + " + y + " = " + ( x + y ); 59 } // subtract complex numbers 62 private void subtractButton_Click( 63 object sender, System.EventArgs e ) 64 { 65 statusLabel.Text = x + " - " + y + " = " + ( x - y ); 66 } // multiply complex numbers 69 private void multiplyButton_Click( 70 object sender, System.EventArgs e ) 71 { 72 statusLabel.Text = x + " * " + y + " = " + ( x * y ); 73 } Use addition operator to add two ComplexNumbers Use subtraction operator to subtract two ComplexNumbers Use multiplication operator to multiply two ComplexNumbers

 2002 Prentice Hall. All rights reserved. Outline 40