Polymorphism. Polymorphism. CSC 330 Object Oriented Programming. What is Polymorphism? Why polymorphism? Class-Object to Base-Class.

Similar documents
CSC330 Object Oriented Programming. Inheritance

Inheritance. Software Engineering with Inheritance. CSC330 Object Oriented Programming. Base Classes and Derived Classes. Class Relationships I

Chapter 9 - Object-Oriented Programming: Polymorphism

CSC 330 Object-Oriented Programming. Encapsulation

Tutorial 6 Enhancing the Inventory Application Introducing Variables, Memory Concepts and Arithmetic

Inheritance (Deitel chapter 9)

Inheritance & Polymorphism Recap. Inheritance & Polymorphism 1

IST311. Advanced Issues in OOP: Inheritance and Polymorphism

Chapter 9 - Object-Oriented Programming: Inheritance

Building non-windows applications (programs that only output to the command line and contain no GUI components).

Inheritance Motivation

Tutorial 5 Completing the Inventory Application Introducing Programming

What is Inheritance?

Making New instances of Classes

Tutorial 19 - Microwave Oven Application Building Your Own Classes and Objects

Part 11 Object Oriented Programming: Inheritance

Polymorphism Part 1 1

Chapter 14 Abstract Classes and Interfaces

Classes in C# namespace classtest { public class myclass { public myclass() { } } }

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

COMP200 - Object Oriented Programming: Test One Duration - 60 minutes

Chapter 5 Object-Oriented Programming

Arrays. Arrays: Declaration and Instantiation. Array: An Array of Simple Values

C++ Important Questions with Answers

First IS-A Relationship: Inheritance

Introduction to Programming Using Java (98-388)

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

Advanced Object-Oriented Programming. 11 Features. C# Programming: From Problem Analysis to Program Design. 4th Edition

Classes. Classes. Classes. Class Circle with methods. Class Circle with fields. Classes and Objects in Java. Introduce to classes and objects in Java.

Abstract Classes and Polymorphism CSC 123 Fall 2018 Howard Rosenthal

Inheritance, Polymorphism, and Interfaces

Inheritance and Polymorphism

Polymorphism (Deitel chapter 10) (Old versions: chapter 9)

Lesson11-Inheritance-Abstract-Classes. The GeometricObject case

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Framework Fundamentals

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

An array can hold values of any type. The entire collection shares a single name

Java Object Oriented Design. CSC207 Fall 2014

CS 162, Lecture 25: Exam II Review. 30 May 2018

CS-202 Introduction to Object Oriented Programming

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

POLYMORPHISM 2 PART. Shared Interface. Discussions. Abstract Base Classes. Abstract Base Classes and Pure Virtual Methods EXAMPLE

Inheriting Windows Forms with Visual C#.NET

CH. 2 OBJECT-ORIENTED PROGRAMMING

Chapter 11: Inheritance

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Inheritance (continued) Inheritance

Java Class Design. Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding

CS105 C++ Lecture 7. More on Classes, Inheritance

More Relationships Between Classes

Operators and Expressions

Object Oriented Programming. Java-Lecture 11 Polymorphism

EECS 1001 and EECS 1030M, lab 01 conflict

25. Generic Programming

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

CS260 Intro to Java & Android 03.Java Language Basics

Chapter 20 - C++ Virtual Functions and Polymorphism

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Inheritance and Polymorphism

(12-1) OOP: Polymorphism in C++ D & D Chapter 12. Instructor - Andrew S. O Fallon CptS 122 (April 3, 2019) Washington State University

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

CS250 Intro to CS II. Spring CS250 - Intro to CS II 1

OBJECT ORİENTATİON ENCAPSULATİON

ECE 3574: Dynamic Polymorphism using Inheritance

Chapter 10 Object-Oriented Programming

ITI Introduction to Computing II

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

Inheritance and Polymorphism

Chapter 9 Objects and Classes. Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved.

C# and.net (1) cont d

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

Introductory Programming Inheritance, sections

Object Oriented Programming. Assistant Lecture Omar Al Khayat 2 nd Year

ITI Introduction to Computing II

JAYARAM COLLEGE OF ENGINEERING AND TECHNOLOGY Pagalavadi, Tiruchirappalli (An approved by AICTE and Affiliated to Anna University)

CS111: PROGRAMMING LANGUAGE II

Polymorphism and Interfaces. CGS 3416 Spring 2018

CSE 8B Programming Assignments Spring Programming: You will have 5 files all should be located in a dir. named PA3:

Web Services in.net (2)

Lecture Notes on Programming Languages

Chapter 10: Inheritance

Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1

Example: Count of Points

Object-Oriented Programming (OOP) Fundamental Principles of OOP

Flag Quiz Application

Computer Science II (20073) Week 1: Review and Inheritance

Advanced C++ Topics. Alexander Warg, 2017

PROGRAMMING IN C AND C++:

Basic Principles of OO. Example: Ice/Water Dispenser. Systems Thinking. Interfaces: Describing Behavior. People's Roles wrt Systems

Table of Contents Preface Bare Necessities... 17

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

Polymorphism. return a.doublevalue() + b.doublevalue();

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Starting Out with Java: From Control Structures Through Objects Sixth Edition

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting

Transcription:

Polymorphism CSC 0 Object Oriented Programming Polymorphism is considered to be a requirement of any true -oriented programming language (OOPL). Reminder: What are the other two essential elements in OOPL? Polymorphism 2 What is Polymorphism? Polymorphism refers to a programming language s ability to process s differently depending on their data type or class. Why polymorphism? With polymorphism, one method can cause different actions to occur, depending on the type of the on which the method is invoked. Number person Me real complex kid adult Teacher Mom Derived-Class Class-Object to Base-Class Class-Object Conversion Class hierarchies Can assign derived-class s to base-class references - A fundamental part of programs that process s polymorphically Can explicitly cast between types in a class hierarchy An of a derived-class can be treated as an of its base-class (The reverse is NOT true, i.e.: base-class is NOT an of any of its derived classes) Can have arrays of base-class references that refer to s of many derived-class types 1 // Point.cs 2 // Point class represents an x-y coordinate Definition pair. of class Point using System; 6 // Point class definition implicitly inherits from Object 7 public class Point // point coordinate private int x, y; 11 12 // default constructor 1 public Point() 1 { 1 // implicit call to Object constructor occurs here } 17 18 // constructor 1 public Point( int xvalue, int yvalue ) 20 { 21 // implicit call to Object constructor occurs here X = xvalue; 2 Y = yvalue; 2 } 2 26 // property X 27 public int X 2 2 get 0 { 1 return x; 2 } Point.cs 6 1

set { 6 x = value; // no need for validation 7 } 8 } // end property X 0 1 // property Y 2 public int Y { get { 6 return y; 7 } 8 set 0 { 1 y = value; // no need for validation 2 } } // end property Y 6 // return string representation of Point 7 public override string ToString() return "[" + X + ", " + Y + "]"; 60 } 61 62 } // end class Point Point.cs 7 1 // Circle.cs 2 // Circle class that inherits from Definition class Point. of class Circle which inherits from class Point using System; 6 // Circle class definition inherits from Point 7 public class Circle : Point private double radius; // circle's radius 11 // default constructor 12 public Circle() 1 { 1 // implicit call to Point constructor occurs here 1 } 17 // constructor 18 public Circle( int xvalue, int yvalue, double radiusvalue ) 1 : base( xvalue, yvalue ) 20 { 21 Radius = radiusvalue; } 2 2 // property Radius 2 public double Radius 26 { 27 get 2 2 return radius; 0 } 1 Circle.cs 8 2 set { if ( value >= 0 ) // validate radius radius = value; 7 8 } // end property Radius 0 // calculate Circle diameter 1 public double Diameter() 2 { return Radius * 2; } 6 // calculate Circle circumference 7 public double Circumference() return Math.PI * Diameter(); 0 } 1 2 // calculate Circle area public virtual double Area() { return Math.PI * Math.Pow( Radius, 2 ); 6 } 7 8 // return string representation of Circle public override string ToString() 60 { 61 return "Center = " + base.tostring() + 62 "; Radius = " + Radius; 6 } 6 6 } // end class Circle Circle.cs 1 // PointCircleTest.cs 2 // Demonstrating inheritance and polymorphism. using System; 8 class PointCircleTest circle1 (derived-class using System.Windows.Forms; Create a Point 6 7 // PointCircleTest class definition Assign Circle Create a Circle PointCircleTest. cs { ) to Point // main entry point for application. Use base-class reference to 11 static void Main( string[] args ) Casts point2 ( downcasts ) reference (baseclass point2 reference) (which - Point access a derived-class 1 Point point1 = new Point( 0, 0 ); references OK since a Circleis-a 1 Circle circle1 = new Circle( 120, 8, 2.7 ); 1 circle1) Point to a Circle string output = "Point point1: " + point1.tostring() and then assigns the + result 17 "\ncircle circle1: " + circle1.tostring(); to the Circle reference 18 1 // use 'is a' relationship to assign circle2. (Cast would be 20 // Circle circle1 to Point reference dangerous if point2 were 21 Point point2 = circle1; referencing a Point! It is 2 output += "\n\nccircle circle1 (via point2): OK since " point2 + 2 point2.tostring(); // Circle s ToString references called, a Circle) not Point s // ToString, since point2 references now a Circle (circle1). // (Object type determines method version, not reference type.) 2 26 // downcast (cast base-class reference to derived-class 27 // data type) point2 to Circle circle2 28 Circle circle2 = ( Circle ) point2; 2 0 output += "\n\ncircle circle1 (via circle2 [and point2]): " + 1 circle2.tostring(); 2 output += "\narea of circle1 (via circle2): " + circle2.area().tostring( "F" ); 11 6 // attempt to assign point1 to Circle reference 7 if ( point1 is Circle ) circle2 = ( Circle ) point1; // Incorrect! Objects may be // cast only to their own type or their base-class types. PointCircleTest. // Here, point1 s own type is Point, and Circle cs // is not a base-class type for Point. output += "\n\ncast successful"; 0 1 } 2 else { output += "\n\npoint1 does not refer to a Circle"; } 6 7 MessageBox.Show( output, Test if point1 references a Circle 8 "Demonstrating the 'is a' relationship" ); it does not since point1 references a Point 0 } // end method Main 1 2 } // end class PointCircleTest Abstract Classes and Methods Concrete classes use the keyword override to provide implementations for all the abstract methods and properties of the base- class 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 2

Case Study: Inheriting from an Abstract Class & Implementation Abstract base class Shape Concretevirtual method Area (default return value is 0) Concretevirtual method Volume (default return value is 0) Abstract read-only property Name Class Point2 inherits from Shape Overrides abstract property Name (required) Does NOT override methods Area and Volume Area = 0 and Volume =0 are correct for a point Class Circle2 inherits from Point2 Overrides property Name Overrides method Area, but not Volume Volume =0 is correct for a circle Class Cylinder2 inherits from Circle2 Overrides property Name Overrides methods Area and Volume 1 implicit inheritance explicit inheritance Object (namespace: System) abstract class Shape Concrete virtual method Area Concrete virtual method Volume Abstract read-only property Name class Point2 Overrides abstract property Name (required) Does NOT override methods Area and Volume (Default return values Area = 0 & Volume =0 are correct for a point) class Circle2 Overrides property Name Overrides method Area, but not Volume (Volume =0 is correct for a circle) class Cylinder2 Overrides property Name Overrides methods Area and Volume 1 1 1 // Point2.cs 2 // Point2 inherits from abstract class Shape and represents // an x-y coordinate pair. using System; 6 // Point2 inherits from abstract class Shape 7 public class Point2 : Shape private int x, y; // Point2 coordinates 11 // default constructor 12 public Point2() 1 { 1 // implicit call to Object constructor occurs here 1 } 17 // constructor 18 public Point2( int xvalue, int yvalue ) 20 X = xvalue; 21 Y = yvalue; } Class Point2 inherits from class Shape 2 2 // property X 2 public int X 26 { 27 get 2 2 return x; 0 } 1 2 set { x = value; needed // no validation } Point2.cs 7 8 // property Y public int Y Point2 s implementation of the 0 { 1 get read-only Name property 2 { return y; } 6 set 8 y = value; validation needed // no } 0 } 1 2 // return string representation of Point2 public override string ToString() { return "[" + X + ", " + Y + "]"; 6 } 7 8 // implement abstract property Name of class Shape public override string Name 60 { 61 get 62 { 6 return "Point2"; 6 } 6 } 66 67 } // end class Point2 Point2.cs 17 1 // Circle2.cs 2 // Circle2 inherits from class Point2 and overrides key members. using System; // Circle2 inherits from class Point2 6 public class Circle2 : Point2 8 private double radius; // Circle2 radius // default constructor 11 public Circle2() 1 // implicit call to Point2 constructor occurs here 1 } 1 // constructor 17 public Circle2( int xvalue, int yvalue, double radiusvalue ) 18 : base( xvalue, yvalue ) 20 Radius = radiusvalue; 21 } Definition of class Circle2 which 2 // property Radius inherits from class Point2 2 public double Radius 2 { 26 get 2 28 return radius; 2 } 0 Circle2.cs 18

1 set 2 { // ensure non-negative radius value if ( value >= 0 ) radius = value; Override the Area method 7 } 8 (defined in class Shape) // calculate Circle2 diameter 0 public double Diameter() 1 { 2 return Radius * 2; } // calculate Circle2 circumference 6 public double Circumference() 8 return Math.PI * Diameter(); } 0 1 // calculate Circle2 area 2 public override double Area() { return Math.PI * Math.Pow( Radius, 2 ); } 6 7 // return string representation of Circle2 8 public override string ToString() { 60 return "Center = " + base.tostring() + 61 "; Radius = " + Radius; 62 } Circle2.cs 1 6 6 // override property Name from class Point2 6 public override string Name 66 { 67 get 6 6 return "Circle2"; 70 } 71 } 72 7 } // end class Circle2 Override the read-only Name property Circle2.cs 20 1 // Cylinder2.cs 2 // Cylinder2 inherits from class Circle2 and overrides key members. using System; // Cylinder2 inherits from class Circle2 6 public class Cylinder2 : Circle2 8 private double height; // Cylinder2 height // default constructor 11 public Cylinder2() 1 // implicit call to Circle2 constructor occurs here 1 } 1 // constructor 17 public Cylinder2( int xvalue, int yvalue, double radiusvalue, 18 double heightvalue ) : base( xvalue, yvalue, radiusvalue ) 20 Height = heightvalue; 21 } 2 // property Height 2 public double Height Class Cylinder2 2 { 26 get derives from Circle2 2 28 return height; 2 } 0 1 set 2 { // ensure non-negative height value if ( value >= 0 ) height = value; Cylinder2.cs 21 Override read-only property Name Cylinder2.cs 7 } 8 // calculate Cylinder2 area 0 public override double Area() 1 { 2 return 2 * base.area() + base.circumference() * Height; } // calculate Cylinder2 volume 6 public override double Volume() 8 return base.area() * Height; } 0 1 // return string representation of Circle2 2 public override string ToString() { return base.tostring() + "; Height = " + Height; } 6 7 // override property Name from class Circle2 8 public override string Name { 60 get Override Area implementation of class Circle2 61 { 62 return "Cylinder2"; 6 } 6 } Override Volume implementation of class Shape 6 66 } // end class Cylinder2 2 1 // AbstractShapesTest.cs 2 // Demonstrates polymorphism in Point-Circle-Cylinder hierarchy. using System; using System.Windows.Forms; Assign a Shape reference AbstractShapesTe 6 public class AbstractShapesTest to reference Create an a array Point2 of Shape s st.cs Assign a Shape reference to 8 public static void Main( string[] args ) reference Assign a a Shape Cylinder2 reference to { Cylinder2 reference s a Circle2 // instantiate Point2, Circle2 and 11 Point2 point = new Point2( 7, 11 ); 12 Circle2 circle = new Circle2(, 8,. ); 1 Cylinder2 cylinder = new Cylinder2(,,., ); 1 1 // create empty array of Shape base-class references Shape[] arrayofshapes = new Shape[ ]; 17 18 // arrayofshapes[ 0 ] refers to Point2 1 arrayofshapes[ 0 ] = point; 20 21 // arrayofshapes[ 1 ] refers to Circle2 arrayofshapes[ 1 ] = circle; 2 2 // arrayofshapes[ 1 ] refers to Cylinder2 2 arrayofshapes[ 2 ] = cylinder; 26 27 string output = point.name + ": " + point + "\n" + 28 circle.name + ": " + circle + "\n" + 2 cylinder.name + ": " + cylinder; 0 1 // display Name, Area and Volume for each 2 // in arrayofshapes polymorphically foreach( Shape shape in arrayofshapes ) { output += "\n\n" + shape.name + ": " + shape + 6 "\narea = " + shape.area().tostring( "F" ) + 7 "\nvolume = " + shape.volume().tostring( "F" ); 8 } 0 MessageBox.Show( output, "Demonstrating Polymorphism" ); 1 } 2 } Use a foreach loop to access every element of the array Rely on polymorphism to call appropriate version of methods 2 AbstractShapesTe st.cs

sealed Methods and Classes sealed is a keyword in C# sealed methods and sealed classes 1)sealed methods cannot be overridden in a derived class Methods that are declared static or private are implicitly sealed 2)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 2 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 2 26 1 // IShape.cs 2 // Interface IShape for Point, Circle, Cylinder Hierarchy. public interface IShape IShape.cs { 6 // classes that implement IShape must implement these methods 7 // and this property 8 double Area(); double Volume(); string Name { get; } Definition of IShape interface 11 } Classes implementing the interface must define methods Area and Volume (each of which take no arguments and return a double) and a read-only string property Name 27 1 // Point.cs 2 // Point implements interface IShape and represents // an x-y coordinate pair. using System; 6 // Point implements IShape interface 7 public class Point : IShape private int x, y; // Point coordinates 11 // default constructor 12 public Point() 1 { 1 // implicit call to Object constructor occurs here 1 } 17 // constructor 18 public Point( int xvalue, int yvalue ) 20 X = xvalue; 21 Y = yvalue; } 2 Class Point implements 2 // property X the IShape interface 2 public int X 26 { 27 get 2 2 return x; 0 } 1 Point.cs 28 2 set { x = value; } 7 Implementation of IShape method Area 8 // property Y public int Y (required), declared virtual to allow 0 { deriving classes to override 1 get 2 { return y; } 6 set 8 y = value; } 0 } 1 2 // return string representation of Point public override string ToString() { return "[" + X + ", " + Y + "]"; 6 } 7 8 // implement interface IShape method Area public virtual double Area() 60 { 61 return 0; 62 } 6 Point.cs 2 6 // implement interface IShape method Volume 6 public virtual double Volume() 66 { 67 return 0; Point.cs 68 } 6 70 // implement property Name of IShape interface 71 public virtual string Name 72 { 7 get Implementation of IShape method 7 return "Point"; Volume (required), declared virtual to 76 } 77 } allow deriving classes to override 78 7 } // end class Point Implementation of IShape property Name (required), declared virtual to allow deriving classes to override 0

1 // Circle.cs 2 // Circle inherits from class Point and overrides key members. using System; // Circle inherits from class Point 6 public class Circle : Point 8 private double radius; // Circle radius // default constructor 11 public Circle() 1 // implicit call to Point constructor occurs here 1 } 1 // constructor 17 public Circle( int xvalue, int yvalue, double radiusvalue ) 18 : base( xvalue, yvalue ) 20 Radius = radiusvalue; 21 } 2 // property Radius Definition of class Circle 2 public double Radius 2 { which inherits from Point 26 get 2 28 return radius; 2 } 0 Circle.cs 1 1 set 2 { // ensure non-negative Radius value if ( value >= 0 ) radius = value; 7 } 8 Override the Point // calculate Circle diameter 0 public double Diameter() implementation of Area 1 { 2 return Radius * 2; } // calculate Circle circumference 6 public double Circumference() 8 return Math.PI * Diameter(); } 0 1 // calculate Circle area 2 public override double Area() { return Math.PI * Math.Pow( Radius, 2 ); } 6 7 // return string representation of Circle 8 public override string ToString() { 60 return "Center = " + base.tostring() + 61 "; Radius = " + Radius; 62 } 6 Circle.cs 2 6 // override property Name from class Point 6 public override string Name 66 { 67 get 6 6 return "Circle"; 70 } 71 } 72 7 } // end class Circle Override the Point implementation of Name Circle.cs 1 // Cylinder.cs 2 // Cylinder inherits from class Circle2 and overrides key members. using System; // Cylinder inherits from class Circle 6 public class Cylinder : Circle 8 private double height; // Cylinder height // default constructor 11 public Cylinder() 1 // implicit call to Circle constructor occurs here 1 } 1 // constructor 17 public Cylinder( int xvalue, int yvalue, double radiusvalue, 18 double heightvalue ) : base( xvalue, yvalue, radiusvalue ) 20 Height = heightvalue; 21 } Declaration of class Cylinder 2 // property Height which inherits from class Circle 2 public double Height 2 { 26 get 2 28 return height; 2 } 0 Cylinder.cs 1 set 2 { Override the Point // ensure non-negative Height value implementation of Volume if ( value >= 0 ) height = value; Override the Circle implementation of Area 7 } 8 // calculate Cylinder area 0 public override double Area() 1 { 2 return 2 * base.area() + base.circumference() * Height; } // calculate Cylinder volume 6 public override double Volume() 8 return base.area() * Height; } 0 1 // return string representation of Cylinder 2 public override string ToString() { return "Center = " + base.tostring() + "; Height = " + Height; 6 } 7 Cylinder.cs 8 // override property Name from class Circle public override string Name 60 { 61 get 62 { 6 return "Cylinder"; 6 } 6 } 66 Override the Circle 67 } // end class Cylinder implementation of Name Cylinder.cs 6 6

7 1 // Interfaces2Test.cs 2 // Demonstrating polymorphism with interfaces in // Point-Circle-Cylinder hierarchy. Create an array of using System.Windows.Forms; Interfaces2Test. IShape references 6 cs (IShape is an 7 public class Interfaces2Test interface) Assign an IShape reference public static void Main( string[] args ) to reference a Point { 11 // instantiate Point, Circle and Cylinder s Assign an IShape reference 12 Point point = new Point( 7, 11 ); 1 Circle circle = new Circle(, 8,. ); to reference a Circle 1 Cylinder cylinder = new Cylinder(,,., ); Assign an IShape reference to 1 // create array of IShape references reference a Cylinder 17 IShape[] arrayofshapes = new IShape[ ]; 18 1 // arrayofshapes[ 0 ] references Point 20 arrayofshapes[ 0 ] = point; 21 // arrayofshapes[ 1 ] references Circle 2 arrayofshapes[ 1 ] = circle; 2 2 // arrayofshapes[ 2 ] references Cylinder 26 arrayofshapes[ 2 ] = cylinder; 27 28 string output = point.name + ": " + point + "\n" + 2 circle.name + ": " + circle + "\n" + 0 cylinder.name + ": " + cylinder; 1 2 foreach ( IShape shape in arrayofshapes ) { output += "\n\n" + shape.name + ":\narea = " + shape.area() + "\nvolume = " + shape.volume(); 7 8 MessageBox.Show( output, "Demonstrating Polymorphism" ); } 0 } Use polymorphism to call the appropriate class s method or property 8 Interfaces2Test. cs Operator Overloading 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. 0 1 // ComplexNumber.cs 2 // Class that overloads operators for adding, subtracting // and multiplying complex numbers. public class ComplexNumber ComplexNumber.cs 6 { 7 private int real; 8 private int imaginary; Property Real provides access to the // default constructor real part of the complex number 11 public ComplexNumber() {} 12 1 // constructor 1 public ComplexNumber( int a, int b ) 1 { Real = a; Class ComplexNumber definition 17 Imaginary = b; 18 } 1 20 // return string representation of ComplexNumber 21 public override string ToString() { 2 return "( " + real + 2 ( imaginary < 0? " - " + ( imaginary * -1 ) : 2 " + " + imaginary ) + "i )"; // conditional operator (?:) 26 } 27 28 // property Real 2 public int Real 0 { 1 get 2 { return real; } 6 set 8 real = value; } 0 Overload the addition (+) operator 1 } // end property Real 2 for ComplexNumbers. // property Imaginary public int Imaginary { 6 get 8 return imaginary; } 0 1 set 2 { Property Imaginary provides imaginary = value; } access to the imaginary part 6 } // end property Imaginary of a complex number 7 8 // overload the addition operator public static ComplexNumber operator + ( 60 ComplexNumber x, ComplexNumber y ) 61 { 62 return new ComplexNumber( 6 x.real + y.real, x.imaginary + y.imaginary ); 6 } // non-overloaded + (for int s) is used above twice 6 // since x.real, y.real, x.imaginary, y.imaginary are all // int s - see Lines 7-8 & 28-6 1 ComplexNumber.cs 2 66 // provide alternative to overloaded + operator 67 // for addition 68 public static ComplexNumber Add( ComplexNumber x, 6 ComplexNumber y ) 70 { ComplexNumber.cs 71 return x + y; // overloaded + Method (just Subtract defined in provides lines -6 an in 72 7 } // this class) used to add 2 ComplexNumbers x & y alternative to the subtraction operator 7 // subtraction operator overload the 7 public static ComplexNumber operator - ( Overloads the multiplication (*) 76 77 ComplexNumber x, ComplexNumber y ) { operator for ComplexNumbers 78 return new ComplexNumber( 7 x.real - y.real, x.imaginary - y.imaginary ); 80 } // non-overloaded - (for int s) is used above twice // since x.real, y.real, x.imaginary, y.imaginary are all // int s - see Lines 7-8 & 28-6 81 82 // provide alternative to overloaded - operator 8 // for subtraction 8 public static ComplexNumber Subtract( ComplexNumber x, 8 ComplexNumber y ) 86 { 87 return x - y; // overloaded - Method (just def. Add in provides lines 7-80 an in this 88 } // class) used to subtract ComplexNumber alternative to y the from addition ComplexNumber operator x 0 8 // overload the multiplication operatoroverload the subtraction (-) 1 public static ComplexNumber operator * ( operator for ComplexNumbers 2 ComplexNumber x, ComplexNumber y ) { return new ComplexNumber( x.real * y.real - x.imaginary * y.imaginary, 6 x.real * y.imaginary + y.real * x.imaginary ); 7 } // non-overloaded *, - and + (for int s) are used above // since x.real, y.real, x.imaginary, y.imaginary are all // int s - see Lines 7-8 & 28-6 7

8 // provide alternative to overloaded * operator 0 // for multiplication 1 public static ComplexNumber Multiply( ComplexNumber x, 2 ComplexNumber y ) { return x * y; // overloaded * (just def. in lines 1-7 in this } // class) used to multiply 2 ComplexNumbers x & y 6 7 } // end class ComplexNumber Note: Method Multiply provides an alternative to the multiplication operator ComplexNumber.cs 1) The alternative methods: public static ComplexNumber Add ( ComplexNumber x, ComplexNumber y ) public static ComplexNumber Subtract ( ComplexNumber x, ComplexNumber y ) public static ComplexNumber Multiply( ComplexNumber x, ComplexNumber y ) 1 // OperatorOverloading.cs 2 // An example that uses operator overloading using System; using System.Drawing; 6 using System.Collections; 7 using System.ComponentModel; 8 using System.Windows.Forms; using System.Data; 11 public class ComplexTest : System.Windows.Forms.Form 1 private System.Windows.Forms.Label reallabel; 1 private System.Windows.Forms.Label imaginarylabel; 1 private System.Windows.Forms.Label statuslabel; 17 private System.Windows.Forms.TextBox realtextbox; 18 private System.Windows.Forms.TextBox imaginarytextbox; 1 20 private System.Windows.Forms.Button firstbutton; 21 private System.Windows.Forms.Button secondbutton; private System.Windows.Forms.Button addbutton; 2 private System.Windows.Forms.Button subtractbutton; 2 private System.Windows.Forms.Button multiplybutton; 2 26 private ComplexNumber x = new ComplexNumber(); 27 private ComplexNumber y = new ComplexNumber(); 28 2 [STAThread] 0 static void Main() 1 { 2 Application.Run( new ComplexTest() ); } OperatorOverload ing.cs private void firstbutton_click( 6 sender, System.EventArgs e ) 8 x.real = Int2.Parse( realtextbox.text ); x.imaginary = Int2.Parse( imaginarytextbox.text ); OperatorOverload 0 realtextbox.clear(); ing.cs 1 imaginarytextbox.clear(); 2 statuslabel.text = "First Complex Number is: " + x; } Use overloaded addition operator to add two ComplexNumbers private void secondbutton_click( 6 sender, System.EventArgs e ) 8 y.real = Int2.Parse( realtextbox.text ); y.imaginary = Int2.Parse( imaginarytextbox.text ); 0 realtextbox.clear(); 1 imaginarytextbox.clear(); Use overloaded subtraction operator 2 statuslabel.text = "Second Complex Number is: " + y; to subtract two ComplexNumbers } // add complex numbers 6 private void addbutton_click( sender, System.EventArgs e ) 8 statuslabel.text = x + " + " + y + " = " + ( x + y ); } 60 61 // subtract complex numbers 62 private void subtractbutton_click( 6 sender, System.EventArgs e ) 6 { 6 statuslabel.text = x + " - " + y + " = " + ( x - y ); 66 } 67 6 68 // multiply complex numbers 6 private void multiplybutton_click( 70 sender, System.EventArgs e ) 71 72 { statuslabel.text = x + " * " + y + " = " + ( x * y ); OperatorOverload 7 } ing.cs 7 7 } // end class ComplexTest Use overloaded multiplication operator to multiply two ComplexNumbers 7 OperatorOverload ing.cs 8