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

Slides:



Advertisements
Similar presentations
Chapter 19 - Inheritance Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
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.
 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.
Object-Oriented Programming in Visual Basic.NET. Overview Defining Classes Creating and Destroying Objects Inheritance Interfaces Working with Classes.
Object-Oriented Programming: Inheritance Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
Object-Oriented Programming: Inheritance
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
Lecture 8 Inheritance Richard Gesick. 2 OBJECTIVES How inheritance promotes software reusability. The concepts of base classes and derived classes. To.
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.
Object Oriented Concepts Classes II. Object Oriented concepts Encapsulation Composition Inheritance Polymorphism.
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.
1 Classes and Controls CE-105 Spring 2007 By: Engr. Faisal ur Rehman.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
These materials where developed by Martin Schray. Please feel free to use and modify them for non-commercial purposes. If you find them useful or would.
 2003 Prentice Hall, Inc. All rights reserved Case Study: Three-Level Inheritance Hierarchy Three level point/circle/cylinder hierarchy –Point.
 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.
Object-Oriented Application Development Using VB.NET 1 Chapter 8 Understanding Inheritance and Interfaces.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 9 - Object-Oriented Programming: Inheritance Outline 9.1 Introduction 9.2 Superclasses and Subclasses.
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
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.
 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.
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.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 19 – Inheritance – Part 1 Outline 19.1Introduction 19.2Inheritance: Base Classes and Derived Classes.
Object-Oriented Programming: Inheritance and Polymorphism.
Chapter 2 11/18/2015 © by Pearson Education, Inc. All Rights Reserved. Lect9 GC 2011.
 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.
 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.
C++ How to Program, 7/e. © by Pearson Education, Inc. All Rights Reserved.2.
CE-105 Spring 2007 By: Engr. Faisal ur Rehman
Chapters 9, 10 – Object-Oriented Programming: Inheritance
Questions from last lesson
Chapter 9 – Object-Oriented Programming: Inheritance
 2002 Prentice Hall. All rights reserved.
Object-Oriented Programming: Inheritance
Object-Oriented Programming: Inheritance
Chapter 11 – Object-Oriented Programming
Chapter 9 Object-Oriented Programming: Inheritance
Week 6 Object-Oriented Programming (2): Polymorphism
Polymorphism, Interfaces &
Object-Oriented Programming: Inheritance
Object-Oriented Programming: Inheritance
Object-Oriented Programming: Inheritance
Presentation transcript:

 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 Conversion 10.3 Type Fields and Select Case Statements 10.4 Polymorphism Examples 10.5 Abstract Classes and Methods 10.6 Case Study: Inheriting Interface and Implementation 10.7 NotInheritable Classes and NotOverridable Methods 10.8 Case Study: Payroll System Using Polymorphism 10.9 Case Study: Creating and Using Interfaces Delegates

 2002 Prentice Hall. All rights reserved Introduction Object Oriented Programming (OOP) –Polymorphism Enables us to write programs that handle a wide variety of related classes and facilitates adding new classes and capabilities to a system Makes it possible to design and implement systems that are easily extensible

 2002 Prentice Hall. All rights reserved Derived-Class-Object to Base-Class- Object Conversion Derived-class –A derived class object can be treated as an object of its base class Base-class object –A 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

 2002 Prentice Hall. All rights reserved. Outline 4 Point.vb 1 ' Fig. 10.1: Point.vb 2 ' CPoint class represents an x-y coordinate pair. 3 4 Public Class CPoint 5 6 ' point coordinate 7 Private mX, mY As Integer 8 9 ' default constructor 10 Public Sub New() ' implicit call to Object constructor occurs here 13 X = 0 14 Y = 0 15 End Sub ' New ' constructor 18 Public Sub New(ByVal xValue As Integer, _ 19 ByVal yValue As Integer) ' implicit call to Object constructor occurs here 22 X = xValue 23 Y = yValue 24 End Sub ' New ' property X 27 Public Property X() As Integer Get 30 Return mX 31 End Get Set(ByVal xValue As Integer) 34 mX = xValue ' no need for validation 35 End Set Declares integer variables mX and mY as Private Sets X and Y to zero Sets xValue and yValue to X and Y

 2002 Prentice Hall. All rights reserved. Outline 5 Point.vb End Property ' X ' property Y 40 Public Property Y() As Integer Get 43 Return mY 44 End Get Set(ByVal yValue As Integer) 47 mY = yValue ' no need for validation 48 End Set End Property ' Y ' return String representation of CPoint 53 Public Overrides Function ToString() As String 54 Return "[" & mX & ", " & mY & "]" 55 End Function ' ToString End Class ' CPoint Method ToString declared as overridable

 2002 Prentice Hall. All rights reserved. Outline 6 Circle.vb 1 ' Fig. 10.2: Circle.vb 2 ' CCircle class that inherits from class CPoint. 3 4 Public Class CCircle 5 Inherits CPoint ' CCircle Inherits from class CPoint 6 7 Private mRadius As Double 8 9 ' default constructor 10 Public Sub New() ' implicit call to CPoint constructor occurs here 13 Radius = 0 14 End Sub ' New ' constructor 17 Public Sub New(ByVal xValue As Integer, _ 18 ByVal yValue As Integer, ByVal radiusValue As Double) ' use MyBase reference to CPoint constructor explicitly 21 MyBase.New(xValue, yValue) 22 Radius = radiusValue 23 End Sub ' New ' property Radius 26 Public Property Radius() As Double Get 29 Return mRadius 30 End Get Set(ByVal radiusValue As Double) 33 Class CCircle inherits class CPoint Sets Radius to 0 as a default value

 2002 Prentice Hall. All rights reserved. Outline 7 Circle.vb 34 If radiusValue >= 0 ' mRadius must be nonnegative 35 mRadius = radiusValue 36 End If End Set End Property ' Radius ' calculate CCircle diameter 43 Public Function Diameter() As Double 44 Return mRadius * 2 45 End Function ' Diameter ' calculate CCircle circumference 48 Public Function Circumference() As Double 49 Return Math.PI * Diameter() 50 End Function ' Circumference ' calculate CCircle area 53 Public Overridable Function Area() As Double 54 Return Math.PI * mRadius ^ 2 55 End Function ' Area ' return String representation of CCircle 58 Public Overrides Function ToString() As String ' use MyBase reference to return CCircle String representation 61 Return "Center= " & MyBase.ToString() & _ 62 "; Radius = " & mRadius 63 End Function ' ToString End Class ' CCircle Ensures radiusValue is greater or equal to zero Methods to calculate Diameter, Circumference, Area and ToString

 2002 Prentice Hall. All rights reserved. Outline 8 Test.vb 1 ' Fig. 10.3: Test.vb 2 ' Demonstrating inheritance and polymorphism. 3 4 Imports System.Windows.Forms 5 6 Class CTest 7 8 ' demonstrate "is a" relationship 9 Shared Sub Main() 10 Dim output As String 11 Dim point1, point2 As CPoint 12 Dim circle1, circle2 As CCircle point1 = New CPoint(30, 50) 15 circle1 = New CCircle(120, 89, 2.7) output = "CPoint point1: " & point1.ToString() & _ 18 vbCrLf & "CCircle circle1: " & circle1.ToString() ' use is-a relationship to assign CCircle to CPoint reference 21 point2 = circle output &= vbCrLf & vbCrLf & _ 24 "CCircle circle1 (via point2): " & point2.ToString() ' downcast (cast base-class reference to derived-class 27 ' data type) point2 to circle2 28 circle2 = CType(point2, CCircle) ' allowed only via cast output &= vbCrLf & vbCrLf & _ 31 "CCircle circle1 (via circle2): " & circle2.ToString() output &= vbCrLf & "Area of circle1 (via circle2): " & _ 34 String.Format("{0:F}", circle2.Area()) 35 Declares two CPoint References Declares two CCircle References Assign a new CPoint object to point1 Assign a new CCircle object to Circle1 Shows the values used to initialize each object Assigns circle1 to point2, a reference to a derived-class object to a base-class reference Invokes method ToString of the CCircle object to which CCircle2 refers to

 2002 Prentice Hall. All rights reserved. Outline 9 Test.vb 36 ' assign CPoint object to CCircle reference 37 If (TypeOf point1 Is CCircle) Then 38 circle2 = CType(point1, CCircle) 39 output &= vbCrLf & vbCrLf & "cast successful" 40 Else 41 output &= vbCrLf & vbCrLf & _ 42 "point1 does not refer to a CCircle" 43 End If MessageBox.Show(output, _ 46 "Demonstrating the 'is a' relationship") 47 End Sub ' Main End Class ' CTest Improper case since point1 references a CPoint object

 2002 Prentice Hall. All rights reserved Type Fields and Select Case Statements Select Case Statements –Select Case structure It allows programmers to distinguish among object types then call upon an appropriate action for a particular object It employs the object that would determine which method to use –Negative Aspects Programmers need to test all possible cases in Select Case After modifying Select-case-based system the programmer needs to insert new cases in all relevant Select Case statements Tracking select-case statements can be time consuming and error prone

 2002 Prentice Hall. All rights reserved Polymorphism Examples CQuadrilaterals –CRectangle –CSquare –CTrapezoid An example of polymorphism is CRectangle, CSquare, and CTrapezoid that are all derived from class CQuadrilaterals Polymorphism –Polymorphism lets the programmer deal with generalities and it promotes extensibility

 2002 Prentice Hall. All rights reserved Abstract Classes and Methods Abstract classes –Abstract classes are incomplete –Normally contains one or more abstract methods or abstract properties –Abstract classes are too generic to define real objects Concrete Classes Provide specifics –A class is made abstract by using keyword MustInherit MustInherit classes must specify their abstract methods or properties –Keyword MustOverride declares a method or property as abstract MustOverride methods and properties do not provide implementations

 2002 Prentice Hall. All rights reserved Case Study: Inheriting Interface and Implementation MustInherit CShape Defines Area and Volume (both return zero by default) –Class CPoint2 (concrete class) Inherits from class CShape and overrides property Name –Class CCircle2 Inherits from class CPoint2 Overrides method Area, and property Name –Class CCylinder2 Inherits from class CCircle2 Overrides method Area, defines method Volume and Specifies property Name

 2002 Prentice Hall. All rights reserved. Outline 14 Shape.vb 1 ' Fig. 10.4: Shape.vb 2 ' Demonstrate a shape hierarchy using MustInherit class. 3 4 Imports System.Windows.Forms 5 6 Public MustInherit Class CShape 7 8 ' return shape area 9 Public Overridable Function Area() As Double 10 Return 0 11 End Function ' Area ' return shape volume 14 Public Overridable Function Volume() As Double 15 Return 0 16 End Function ' Volume ' overridable method that should return shape name 19 Public MustOverride ReadOnly Property Name() As String End Class ' CShape Class CShape declared as MustInherit or abstract Keyword Overridable must accompany every method in MustInherit class

 2002 Prentice Hall. All rights reserved. Outline 15 Point2.vb 1 ' Fig. 10.5: Point2.vb 2 ' CPoint2 class represents an x-y coordinate pair. 3 4 Public Class CPoint2 5 Inherits CShape ' CPoint2 inherits from MustInherit class CShape 6 7 ' point coordinate 8 Private mX, mY As Integer 9 10 ' default constructor 11 Public Sub New() ' implicit call to Object constructor occurs here 14 X = 0 15 Y = 0 16 End Sub ' New ' constructor 19 Public Sub New(ByVal xValue As Integer, _ 20 ByVal yValue As Integer) ' implicit call to Object constructor occurs here 23 X = xValue 24 Y = yValue 25 End Sub ' New ' property X 28 Public Property X() As Integer Get 31 Return mX 32 End Get 33 Class CPoint2 inherits class CShape Sets both variables to zero Class CPoint2 provides member variables mX and mY

 2002 Prentice Hall. All rights reserved. Outline 16 Point2.vb 34 Set(ByVal xValue As Integer) 35 mX = xValue ' no need for validation 36 End Set End Property ' X ' property Y 41 Public Property Y() As Integer Get 44 Return mY 45 End Get Set(ByVal yValue As Integer) 48 mY = yValue ' no need for validation 49 End Set End Property ' Y ' return String representation of CPoint2 54 Public Overrides Function ToString() As String 55 Return "[" & mX & ", " & mY & "]" 56 End Function ' ToString ' implement MustOverride property of class CShape 59 Public Overrides ReadOnly Property Name() As String Get 62 Return "CPoint2" 63 End Get End Property ' Name End Class ' CPoint2 Class CPoint2 implements property Name

 2002 Prentice Hall. All rights reserved. Outline 17 Circle2.vb 1 ' Fig. 10.6: Circle2.vb 2 ' CCircle2 class inherits from CPoint2 and overrides key members. 3 4 Public Class CCircle2 5 Inherits CPoint2 ' CCircle2 Inherits from class CPoint2 6 7 Private mRadius As Double 8 9 ' default constructor 10 Public Sub New() ' implicit call to CPoint2 constructor occurs here 13 Radius = 0 14 End Sub ' New ' constructor 17 Public Sub New(ByVal xValue As Integer, _ 18 ByVal yValue As Integer, ByVal radiusValue As Double) ' use MyBase reference to CPoint2 constructor explicitly 21 MyBase.New(xValue, yValue) 22 Radius = radiusValue 23 End Sub ' New ' property Radius 26 Public Property Radius() As Double Get 29 Return mRadius 30 End Get Set(ByVal radiusValue As Double) If radiusValue >= 0 ' mRadius must be nonnegative 35 mRadius = radiusValue Class CCircle2 inherits from class CPoint2 Class CCircle2 provides member variable mRadius Property Radius

 2002 Prentice Hall. All rights reserved. Outline 18 Circle2.vb 36 End If End Set End Property ' Radius ' calculate CCircle2 diameter 43 Public Function Diameter() As Double 44 Return mRadius * 2 45 End Function ' Diameter ' calculate CCircle2 circumference 48 Public Function Circumference() As Double 49 Return Math.PI * Diameter() 50 End Function ' Circumference ' calculate CCircle2 area 53 Public Overrides Function Area() As Double 54 Return Math.PI * mRadius ^ 2 55 End Function ' Area ' return String representation of CCircle2 58 Public Overrides Function ToString() As String ' use MyBase to return CCircle2 String representation 61 Return "Center = " & MyBase.ToString() & _ 62 "; Radius = " & mRadius 63 End Function ' ToString ' override property Name from class CPoint2 66 Public Overrides ReadOnly Property Name() As String Get 69 Return "CCircle2" 70 End Get Method Area declared as overridableMethod to calculate Diameter and CircumferenceDefines function ToString as overridable Defines function Name as ReadOnly and overridable that returns name CCircle2

 2002 Prentice Hall. All rights reserved. Outline 19 Circle2.vb End Property ' Name End Class ' CCircle2

 2002 Prentice Hall. All rights reserved. Outline 20 Cylinder2.vb 1 ' Fig. 10.7: Cylinder2.vb 2 ' CCylinder2 inherits from CCircle2 and overrides key members. 3 4 Public Class CCylinder2 5 Inherits CCircle2 ' CCylinder2 inherits from class CCircle2 6 7 Protected mHeight As Double 8 9 ' default constructor 10 Public Sub New() ' implicit call to CCircle2 constructor occurs here 13 Height = 0 14 End Sub ' New ' four-argument constructor 17 Public Sub New(ByVal xValue As Integer, _ 18 ByVal yValue As Integer, ByVal radiusValue As Double, _ 19 ByVal heightValue As Double) ' explicit call to CCircle2 constructor 22 MyBase.New(xValue, yValue, radiusValue) 23 Height = heightValue ' set CCylinder2 height 24 End Sub ' New ' property Height 27 Public Property Height() As Double Get 30 Return mHeight 31 End Get ' set CCylinder2 height if argument value is positive 34 Set(ByVal heightValue As Double) 35 Class CCylinder2 inherits class CCircle2 Class CCylinder2 contains a member variable mHeight Property Height

 2002 Prentice Hall. All rights reserved. Outline 21 Cylinder2.vb 36 If heightValue >= 0 Then ' mHeight must be nonnegative 37 mHeight = heightValue 38 End If End Set End Property ' Height ' override method Area to calculate CCylinder2 surface area 45 Public Overrides Function Area() As Double 46 Return 2 * MyBase.Area + MyBase.Circumference * mHeight 47 End Function ' Area ' calculate CCylinder2 volume 50 Public Overrides Function Volume() As Double 51 Return MyBase.Area * mHeight 52 End Function ' Volume ' convert CCylinder2 to String 55 Public Overrides Function ToString() As String 56 Return MyBase.ToString() & "; Height = " & mHeight 57 End Function ' ToString ' override property Name from class CCircle2 60 Public Overrides ReadOnly Property Name() As String Get 63 Return "CCylinder2" 64 End Get End Property ' Name End Class ' CCylinder2 Overrides methods Area, Volume and ToString Defines function Name as ReadOnly and overridable that returns name CCylinder

 2002 Prentice Hall. All rights reserved. Outline 22 Test2.vb 1 ' Fig. 10.8: Test2.vb 2 ' Demonstrate polymorphism in Point-Circle-Cylinder hierarchy. 3 4 Imports System.Windows.Forms 5 6 Class CTest2 7 8 Shared Sub Main() 9 10 ' instantiate CPoint2, CCircle2 and CCylinder2 objects 11 Dim point As New CPoint2(7, 11) 12 Dim circle As New CCircle2(22, 8, 3.5) 13 Dim cylinder As New CCylinder2(10, 10, 3.3, 10) ' instantiate array of base-class references 16 Dim arrayOfShapes As CShape() = New CShape(2){} ' arrayOfShapes(0) refers to CPoint2 object 19 arrayOfShapes(0) = point ' arrayOfShapes(1) refers to CCircle2 object 22 arrayOfShapes(1) = circle ' arrayOfShapes(2) refers to CCylinder2 object 25 arrayOfShapes(2) = cylinder Dim output As String = point.Name & ": " & _ 28 point.ToString() & vbCrLf & circle.Name & ": " & _ 29 circle.ToString() & vbCrLf & cylinder.Name & _ 30 ": " & cylinder.ToString() Dim shape As CShape 33 Declares CPoint2 object point, CCircle2 object circle, and CCylinder2 object cylinder Declares an array arrayOfShapes which contains three CShape references Assigns reference Circle to array element arrayOfShapes(1) Invokes property Name and method ToString for each object Uses derived-class references to invoke each derived-class object’s methods and properties

 2002 Prentice Hall. All rights reserved. Outline 23 Test2.vb 34 ' display name, area and volume for each object in 35 ' arrayOfShapes polymorphically 36 For Each shape In arrayOfShapes 37 output &= vbCrLf & vbCrLf & shape.Name & ": " & _ 38 shape.ToString() & vbCrLf & "Area = " & _ 39 String.Format("{0:F}", shape.Area) & vbCrLf & _ 40 "Volume = " & String.Format("{0:F}", shape.Volume) 41 Next MessageBox.Show(output, "Demonstrating Polymorphism") 44 End Sub ' Main End Class ' CTest2 Uses base-class CShape references to invoke each derived-class object’s methods and properties

 2002 Prentice Hall. All rights reserved NottInheritable Classes and NotOverridable Methods NottInheritable Classes –Must be concrete class and it is the “opposite” of MustInherit – Cannot be a base class NotOverridable –A method that was instantiated Overridable in a base class can be instantiated NotOverridable in a derived class –Methods that are declared Shared and methods that are declared Private implicitly are not NotOverridable

 2002 Prentice Hall. All rights reserved Case Study: Payroll System Using Polymorphism Class CEmployee –Derived classes of CEmployee are CCommisionerWorker, CPieceWorker and CHourlyWorker If classes are declared as NotInheritable then no other classes can be derived from them Each class derived from CEmployee requires its own definition of method Earnings, hence keyword MustOverride is attached to Earnings

 2002 Prentice Hall. All rights reserved. Outline 26 Employee.vb 1 ' Fig. 10.9: Employee.vb 2 ' Abstract base class for employee derived classes. 3 4 Public MustInherit Class CEmployee 5 6 Private mFirstName As String 7 Private mLastName As String 8 9 ' constructor 10 Public Sub New(ByVal firstNameValue As String, _ 11 ByVal lastNameValue As String) FirstName = firstNameValue 14 LastName = lastNameValue 15 End Sub ' New ' property FirstName 18 Public Property FirstName() As String Get 21 Return mFirstName 22 End Get Set(ByVal firstNameValue As String) 25 mFirstName = firstNameValue 26 End Set End Property ' FirstName ' property LastName 31 Public Property LastName() As String Get 34 Return mLastName 35 End Get Declares two Private variables mFirstName and mLastName as strings Takes two arguments firstNameValue and lastNameValue Property FirstName and LastName Keyword MustInherit indicates that class CEmployee is abstract

 2002 Prentice Hall. All rights reserved. Outline 27 Employee.vb Set(ByVal lastNameValue As String) 38 mLastName = lastNameValue 39 End Set End Property ' LastName ' obtain String representation of employee 44 Public Overrides Function ToString() As String 45 Return mFirstName & " " & mLastName 46 End Function ' ToString ' abstract method that must be implemented for each derived 49 ' class of CEmployee to calculate specific earnings 50 Public MustOverride Function Earnings() As Decimal End Class ' CEmployee Keyword MustOverride is attached to method Earnings

 2002 Prentice Hall. All rights reserved. Outline 28 Boss.vb 1 ' Fig : Boss.vb 2 ' Boss class derived from CEmployee. 3 4 Public NotInheritable Class CBoss 5 Inherits CEmployee 6 7 Private mSalary As Decimal 8 9 ' constructor for class CBoss 10 Public Sub New(ByVal firstNameValue As String, _ 11 ByVal lastNameValue As String, ByVal salaryValue As Decimal) MyBase.New(firstNameValue, lastNameValue) 14 WeeklySalary = salaryValue 15 End Sub ' New ' property WeeklySalary 18 Public Property WeeklySalary() As Decimal Get 21 Return mSalary 22 End Get Set(ByVal bossSalaryValue As Decimal) ' validate mSalary 27 If bossSalaryValue > 0 28 mSalary = bossSalaryValue 29 End If End Set End Property ' WeeklySalary 34 NotInheritable class CBoss inherits CEmloyee Class CBoss’s constructor receives three arguments Passes first name and last name to the CEmployee constructor Gets the value for member variable mSalary Sets the value of member variable mSalary and ensures that it cannot hold a negative value

 2002 Prentice Hall. All rights reserved. Outline 29 Boss.vb 35 ' override base-class method to calculate Boss earnings 36 Public Overrides Function Earnings() As Decimal 37 Return WeeklySalary 38 End Function ' Earnings ' return Boss' name 41 Public Overrides Function ToString() As String 42 Return "CBoss: " & MyBase.ToString() 43 End Function ' ToString End Class ' CBoss Defines method Earnings Returns a string indicating the type of employee

 2002 Prentice Hall. All rights reserved. Outline 30 CommissionWorker.vb 1 ' Fig : CommissionWorker.vb 2 ' CEmployee implementation for a commission worker. 3 4 Public NotInheritable Class CCommissionWorker 5 Inherits CEmployee 6 7 Private mSalary As Decimal ' base salary per week 8 Private mCommission As Decimal ' amount per item sold 9 Private mQuantity As Integer ' total items sold ' constructor for class CCommissionWorker 12 Public Sub New(ByVal firstNameValue As String, _ 13 ByVal lastNameValue As String, ByVal salaryValue As Decimal, _ 14 ByVal commissionValue As Decimal, _ 15 ByVal quantityValue As Integer) MyBase.New(firstNameValue, lastNameValue) 18 Salary = salaryValue 19 Commission = commissionValue 20 Quantity = quantityValue 21 End Sub ' New ' property Salary 24 Public Property Salary() As Decimal Get 27 Return mSalary 28 End Get Set(ByVal salaryValue As Decimal) ' validate mSalary 33 If salaryValue > 0 Then 34 mSalary = salaryValue 35 End If NotInheritable class CCommissionWorker inherits CEmloyee Constructor for this class receives four arguments Passes first and last name to the base-class CEmployee constructor by using keyword MyBase Ensures SalaryValue is positive

 2002 Prentice Hall. All rights reserved. Outline 31 CommissionWorker.vb End Set End Property ' Salary ' property Commission 42 Public Property Commission() As Decimal Get 45 Return mCommission 46 End Get Set(ByVal commissionValue As Decimal) ' validate mCommission 51 If commissionValue > 0 Then 52 mCommission = commissionValue 53 End If End Set End Property ' Commission ' property Quantity 60 Public Property Quantity() As Integer Get 63 Return mQuantity 64 End Get Set(ByVal QuantityValue As Integer) 67 Ensures CommisionValue is positive

 2002 Prentice Hall. All rights reserved. Outline 32 CommissionWorker.vb 68 ' validate mQuantity 69 If QuantityValue > 0 Then 70 mQuantity = QuantityValue 71 End If End Set End Property ' Quantity ' override method to calculate CommissionWorker earnings 78 Public Overrides Function Earnings() As Decimal 79 Return Salary + Commission * Quantity 80 End Function ' Earnings ' return commission worker's name 83 Public Overrides Function ToString() As String 84 Return "CCommissionWorker: " & MyBase.ToString() 85 End Function ' ToString End Class ' CCommissionWorker Defines method Earnings Returns a string indicating the type of employee Ensures QuantityValue is positive

 2002 Prentice Hall. All rights reserved. Outline 33 PieceWorker.vb 1 ' Fig : PieceWorker.vb 2 ' CPieceWorker class derived from CEmployee. 3 4 Public NotInheritable Class CPieceWorker 5 Inherits CEmployee 6 7 Private mAmountPerPiece As Decimal ' wage per piece output 8 Private mQuantity As Integer ' output per week 9 10 ' constructor for CPieceWorker 11 Public Sub New(ByVal firstNameValue As String, _ 12 ByVal lastNameValue As String, _ 13 ByVal wagePerPieceValue As Decimal, _ 14 ByVal quantityValue As Integer) MyBase.New(firstNameValue, lastNameValue) 17 WagePerPiece = wagePerPieceValue 18 Quantity = quantityValue 19 End Sub ' New ' property WagePerPiece 22 Public Property WagePerPiece() As Decimal Get 25 Return mAmountPerPiece 26 End Get Set(ByVal wagePerPieceValue As Decimal) ' validate mAmountPerPiece 31 If wagePerPieceValue > 0 Then 32 mAmountPerPiece = wagePerPieceValue 33 End If End Set NotInheritable class CPieceWorker inherits CEmloyee Constructor for CPieceWorker receives four arguments Passes first name and last name to the base-class CEmployee Constructor Validates that wagePerPieceValue is greater than zero

 2002 Prentice Hall. All rights reserved. Outline 34 PieceWorker.vb End Property ' WagePerPiece ' property Quantity 40 Public Property Quantity() As Integer Get 43 Return mQuantity 44 End Get Set(ByVal quantityValue As Integer) ' validate mQuantity 49 If quantityValue > 0 Then 50 mQuantity = quantityValue 51 End If End Set End Property ' Quantity ' override base-class method to calculate PieceWorker's earnings 58 Public Overrides Function Earnings() As Decimal 59 Return Quantity * WagePerPiece 60 End Function ' Earnings ' return piece worker's name 63 Public Overrides Function ToString() As String 64 Return "CPieceWorker: " & MyBase.ToString() 65 End Function ' ToString End Class ' CPieceWorker Method Earnings calculates a piece worker’s earnings Method ToString returns a string indicating the type of employee Validates that quantityValue is greater than 0

 2002 Prentice Hall. All rights reserved. Outline 35 HourlyWorker.vb 1 ' Fig : HourlyWorker.vb 2 ' CEmployee implementation for an hourly worker. 3 4 Public NotInheritable Class CHourlyWorker 5 Inherits CEmployee 6 7 Private mWage As Decimal ' wage per hour 8 Private mHoursWorked As Double ' hours worked for week 9 10 ' constructor for class CHourlyWorker 11 Public Sub New(ByVal firstNameValue As String, _ 12 ByVal lastNameValue As String, _ 13 ByVal wageValue As Decimal, ByVal hourValue As Double) MyBase.New(firstNameValue, lastNameValue) 16 HourlyWage = wageValue 17 Hours = hourValue 18 End Sub ' New ' property HourlyWage 21 Public Property HourlyWage() As Decimal Get 24 Return mWage 25 End Get Set(ByVal hourlyWageValue As Decimal) ' validate mWage 30 If hourlyWageValue > 0 Then 31 mWage = hourlyWageValue 32 End If End Set 35 Class CPieceWorker inherits from class CEmloyee Constructor for this class receives four arguments Passes first and last name to the base-class CEmployee constructor Validates variable hourlyWageValue is greater than zero

 2002 Prentice Hall. All rights reserved. Outline 36 HourlyWorker.vb 36 End Property ' HourlyWage ' property Hours 39 Public Property Hours() As Double Get 42 Return mHoursWorked 43 End Get Set(ByVal hourValue As Double) ' validate mHoursWorked 48 If hourValue > 0 Then 49 mHoursWorked = hourValue 50 End If End Set End Property ' Hours ' override base-class method to calculate HourlyWorker earnings 57 Public Overrides Function Earnings() As Decimal ' calculate for "time-and-a-half" 60 If mHoursWorked <= Return Convert.ToDecimal(mWage * mHoursWorked) 62 Else 63 Return Convert.ToDecimal((mWage * mHoursWorked) + _ 64 (mHoursWorked - 40) * 0.5 * mWage) 65 End If End Function ' Earnings 68 Validates that hourValue is greater than zero Defines method Earnings

 2002 Prentice Hall. All rights reserved. Outline 37 HourlyWorker.vb 69 ' return hourly worker's name 70 Public Overrides Function ToString() As String 71 Return "CHourlyWorker: " & MyBase.ToString() 72 End Function ' ToString End Class ' CHourlyWorker Method ToString returns a string indicating the type of employee

 2002 Prentice Hall. All rights reserved. Outline 38 Test.vb 1 ' Fig 10.14: Test.vb 2 ' Displays the earnings for each CEmployee. 3 4 Imports System.Windows.Forms 5 6 Class CTest 7 8 Shared Sub Main() 9 Dim employee As CEmployee ' base-class reference 10 Dim output As String Dim boss As CBoss = New CBoss("John", "Smith", 800) Dim commissionWorker As CCommissionWorker = _ 15 New CCommissionWorker("Sue", "Jones", 400, 3, 150) Dim pieceWorker As CPieceWorker = _ 18 New CPieceWorker("Bob", "Lewis", _ 19 Convert.ToDecimal(2.5), 200) Dim hourlyWorker As CHourlyWorker = _ 22 New CHourlyWorker("Karen", "Price", _ 23 Convert.ToDecimal(13.75), 40) ' employee reference to a CBoss 26 employee = boss 27 output &= GetString(employee) & boss.ToString() & _ 28 " earned " & boss.Earnings.ToString("C") & vbCrLf & vbCrLf ' employee reference to a CCommissionWorker 31 employee = commissionWorker 32 output &= GetString(employee) & _ 33 commissionWorker.ToString() & " earned " & _ 34 commissionWorker.Earnings.ToString("C") & vbCrLf & vbCrLf 35 Assigns to CBoss reference boss a CBoss object Passes the bosses first and last name with a weekly salary Sets the derived-class reference boss to the base-class CEmployee reference employee Passes reference employee as an argument to Private method GetString

 2002 Prentice Hall. All rights reserved. Outline 39 Test.vb 36 ' employee reference to a CPieceWorker 37 employee = pieceWorker 38 output &= GetString(employee) & pieceWorker.ToString() & _ 39 " earned " & pieceWorker.Earnings.ToString("C") _ 40 & vbCrLf & vbCrLf ' employee reference to a CHourlyWorker 43 employee = hourlyWorker 44 output &= GetString(employee) & _ 45 hourlyWorker.ToString() & " earned " & _ 46 hourlyWorker.Earnings.ToString("C") & vbCrLf & vbCrLf MessageBox.Show(output, "Demonstrating Polymorphism", _ 49 MessageBoxButtons.OK, MessageBoxIcon.Information) 50 End Sub ' Main ' return String containing employee information 53 Shared Function GetString(ByVal worker As CEmployee) As String 54 Return worker.ToString() & " earned " & _ 55 worker.Earnings.ToString("C") & vbCrLf 56 End Function ' GetString End Class ' CTest Invokes CBoss method Earnings Invokes CBoss method ToString Assigns the derived-class reference pieceWorker to the base-class CEmployee reference employee

 2002 Prentice Hall. All rights reserved. Outline 40 Test.vb

 2002 Prentice Hall. All rights reserved Case Study: Creating and Using Interfaces Interface –An interface is used when there is no default implementation to inherit – Interface definition begins with keyword Interface Contains a list of Public methods and properties –Interface provide a uniform set of methods and properties to objects of disparate classes

 2002 Prentice Hall. All rights reserved. Outline 42 IAge.vb 1 ' Fig : IAge.vb 2 ' Interface IAge declares property for setting and getting age. 3 4 Public Interface IAge 5 6 ' classes that implement IAge must define these properties 7 ReadOnly Property Age() As Integer 8 ReadOnly Property Name() As String 9 10 End Interface ' IAge Definition of interface IAgeSpecify properties Age and Name

 2002 Prentice Hall. All rights reserved. Outline 43 Person.vb 1 ' Fig : Person.vb 2 ' Class CPerson has a birthday. 3 4 Public Class CPerson 5 Implements IAge 6 7 Private mYearBorn As Integer 8 Private mFirstName As String 9 Private mLastName As String ' constructor receives first name, last name and birth date 12 Public Sub New(ByVal firstNameValue As String, _ 13 ByVal lastNameValue As String, _ 14 ByVal yearBornValue As Integer) ' implicit call to Object constructor 17 mFirstName = firstNameValue 18 mLastName = lastNameValue ' validate year 21 If (yearBornValue > 0 AndAlso _ 22 yearBornValue <= Date.Now.Year) mYearBorn = yearBornValue 25 Else 26 mYearBorn = Date.Now.Year 27 End If End Sub ' New ' property Age implementation of interface IAge 32 ReadOnly Property Age() As Integer _ 33 Implements IAge.Age 34 Keyword Implements indicates that class CPerson implements interface IAge Member variables of class CPerson Constructor takes three arguments and sets the values Definition of Age

 2002 Prentice Hall. All rights reserved. Outline 44 Person.vb 35 Get 36 Return Date.Now.Year - mYearBorn 37 End Get End Property ' Age ' property Name implementation of interface IAge 42 ReadOnly Property Name() As String _ 43 Implements IAge.Name Get 46 Return mFirstName & " " & mLastName 47 End Get End Property ' Name End Class ' CPerson Definition of Name

 2002 Prentice Hall. All rights reserved. Outline 45 Tree.vb 1 ' Fig : Tree.vb 2 ' Class CTree contains number of rings corresponding to age. 3 4 Public Class CTree 5 Implements IAge 6 7 Private mRings As Integer 8 9 ' constructor receives planting date 10 Public Sub New(ByVal yearPlanted As Integer) ' implicit call to Object constructor 13 mRings = Date.Now.Year - yearPlanted 14 End Sub ' New ' increment mRings 17 Public Sub AddRing() 18 mRings += 1 19 End Sub ' AddRing ' property Age 22 ReadOnly Property Age() As Integer _ 23 Implements IAge.Age Get 26 Return mRings 27 End Get End Property ' Age ' property Name implementation of interface IAge 32 ReadOnly Property Name() As String _ 33 Implements IAge.Name 34 Class CTree implements interface IAge Class CTree contains member variables mRings CTree constructor takes one argument Class CTree includes method AddRing Definition of Age and Name

 2002 Prentice Hall. All rights reserved. Outline 46 Tree.vb 35 Get 36 Return "Tree" 37 End Get End Property ' Name End Class ' CTree

 2002 Prentice Hall. All rights reserved. Outline 47 Test.vb 1 ' Fig : Test.vb 2 ' Demonstrate polymorphism. 3 4 Imports System.Windows.Forms 5 6 Class CTest 7 8 Shared Sub Main() 9 10 ' instantiate CTree and CPerson objects 11 Dim tree As New CTree(1976) 12 Dim person As New CPerson("Bob", "Jones", 1983) ' instantiate array of interface references 15 Dim iAgeArray As IAge() = New IAge(1){} ' iAgeArray(0) references CTree object 18 iAgeArray(0) = tree ' iAgeArray(1) references CPerson object 21 iAgeArray(1) = person ' display tree information 24 Dim output As String = tree.ToString() & ": " & _ 25 tree.Name & vbCrLf & "Age is " & tree.Age & vbCrLf & _ 26 vbCrLf ' display person information 29 output &= person.ToString() & ": " & _ 30 person.Name & vbCrLf & "Age is " & person.Age & _ 31 vbCrLf Dim ageReference As IAge 34 Instantiates object tree of class CTreeDeclares object person of class CPerson Declares IAgeArray of two references to IAge Object Invokes method ToString on treeInvokes method ToString on person

 2002 Prentice Hall. All rights reserved. Outline 48 Test.vb 35 ' display name and age for each IAge object in iAgeArray 36 For Each ageReference In iAgeArray 37 output &= vbCrLf & ageReference.Name & ": " & _ 38 "Age is " & ageReference.Age 39 Next MessageBox.Show(output, "Demonstrating Polymorphism") 42 End Sub ' Main End Class ' CTest Defines For Each structure

 2002 Prentice Hall. All rights reserved. Outline 49 Shape.vb 1 ' Fig : Shape.vb 2 ' Interface IShape for Point, Circle, Cylinder hierarchy. 3 4 Public Interface IShape 5 6 ' classes that implement IShape must define these methods 7 Function Area() As Double 8 Function Volume() As Double 9 ReadOnly Property Name() As String End Interface ' IShape Defines interface IShapeSpecifies two methods and one property Name

 2002 Prentice Hall. All rights reserved. Outline 50 Point3.vb 1 ' Fig : Point3.vb 2 ' Class CPoint3 implements IShape. 3 4 Public Class CPoint3 5 Implements IShape 6 7 ' point coordinate 8 Private mX, mY As Integer 9 10 ' default constructor 11 Public Sub New() 12 X = 0 13 Y = 0 14 End Sub ' New ' constructor 17 Public Sub New(ByVal xValue As Integer, _ 18 ByVal yValue As Integer) 19 X = xValue 20 Y = yValue 21 End Sub ' New ' property X 24 Public Property X() As Integer Get 27 Return mX 28 End Get Set(ByVal xValue As Integer) 31 mX = xValue ' no need for validation 32 End Set End Property ' X 35 Class Cpoint3 implements interface IShape Declares two Private integers mX and mY Property X

 2002 Prentice Hall. All rights reserved. Outline 51 Point3.vb 36 ' property Y 37 Public Property Y() As Integer Get 40 Return mY 41 End Get Set(ByVal yValue As Integer) 44 mY = yValue ' no need for validation 45 End Set End Property ' Y ' return String representation of CPoint3 50 Public Overrides Function ToString() As String 51 Return "[" & mX & ", " & mY & "]" 52 End Function ' ToString ' implement interface IShape method Area 55 Public Overridable Function Area() As Double _ 56 Implements IShape.Area Return 0 59 End Function ' Area ' implement interface IShape method Volume 62 Public Overridable Function Volume() As Double _ 63 Implements IShape.Volume Return 0 66 End Function ' Volume ' implement interface IShape property Name 69 Public Overridable ReadOnly Property Name() As String _ 70 Implements IShape.Name Property Y Declares method Area as overridableReturns zero for the AreaInstantiates method Volume as OverridableReturns zero for VolumeInstantiates Property Name as Overridable

 2002 Prentice Hall. All rights reserved. Outline 52 Point3.vb Get 73 Return "CPoint3" 74 End Get End Property ' Name End Class ' CPoint3 Returns class name as a String

 2002 Prentice Hall. All rights reserved. Outline 53 Circle3.vb 1 ' Fig : Circle3.vb 2 ' CCircle3 inherits CPoint3 and overrides some of its methods. 3 4 Public Class CCircle3 5 Inherits CPoint3 ' CCircle3 Inherits from class CPoint3 6 7 Private mRadius As Double 8 9 ' default constructor 10 Public Sub New() 11 Radius = 0 12 End Sub ' New ' constructor 15 Public Sub New(ByVal xValue As Integer, _ 16 ByVal yValue As Integer, ByVal radiusValue As Double) ' use MyBase reference to CPoint constructor explicitly 19 MyBase.New(xValue, yValue) 20 Radius = radiusValue 21 End Sub ' New ' property Radius 24 Public Property Radius() As Double Get 27 Return mRadius 28 End Get Set(ByVal radiusValue As Double) If radiusValue >= 0 33 mRadius = radiusValue ' mRadius cannot be negative 34 End If 35 Class CCircle3 inherits CPoint3 Declares Private member variable mRadius

 2002 Prentice Hall. All rights reserved. Outline 54 Circle3.vb 36 End Set End Property ' Radius ' calculate CCircle3 diameter 41 Public Function Diameter() As Double 42 Return mRadius * 2 43 End Function ' Diameter ' calculate CCircle3 circumference 46 Public Function Circumference() As Double 47 Return Math.PI * Diameter() 48 End Function ' Circumference ' calculate CCircle3 area 51 Public Overrides Function Area() As Double 52 Return Math.PI * mRadius ^ 2 53 End Function ' Area ' override interface IShape property Name from class CPoint3 56 Public ReadOnly Overrides Property Name() As String Get 59 Return "CCircle3" 60 End Get End Property ' Name ' return String representation of CCircle3 65 Public Overrides Function ToString() As String ' use MyBase to return CCircle3 String representation 68 Return "Center = " & MyBase.ToString() & _ 69 "; Radius = " & mRadius 70 End Function ' ToString Calculates Area and for class CCircle3Returns class name CCircle3

 2002 Prentice Hall. All rights reserved. Outline 55 Circle3.vb End Class ' CCircle3

 2002 Prentice Hall. All rights reserved. Outline 56 Cylinder3.vb 1 ' Fig : Cylinder3.vb 2 ' CCylinder3 inherits from CCircle3 and overrides key members. 3 4 Public Class CCylinder3 5 Inherits CCircle3 ' CCylinder3 inherits from class CCircle3 6 7 Protected mHeight As Double 8 9 ' default constructor 10 Public Sub New() 11 Height = 0 12 End Sub ' New ' four-argument constructor 15 Public Sub New(ByVal xValue As Integer, _ 16 ByVal yValue As Integer, ByVal radiusValue As Double, _ 17 ByVal heightValue As Double) ' explicit call to CCircle2 constructor 20 MyBase.New(xValue, yValue, radiusValue) 21 Height = heightValue ' set CCylinder2 height 22 End Sub ' New ' property Height 25 Public Property Height() As Double Get 28 Return mHeight 29 End Get ' set CCylinder3 height if argument value is positive 32 Set(ByVal heightValue As Double) If heightValue >= 0 Then 35 mHeight = heightValue Class CCylinder3 inherits from class CCircle3

 2002 Prentice Hall. All rights reserved. Outline 57 Cylinder3.vb 36 End If End Set End Property ' Height ' override method Area to calculate CCylinder2 area 43 Public Overrides Function Area() As Double 44 Return 2 * MyBase.Area + MyBase.Circumference * mHeight 45 End Function ' Area ' calculate CCylinder3 volume 48 Public Overrides Function Volume() As Double 49 Return MyBase.Area * mHeight 50 End Function ' Volume ' convert CCylinder3 to String 53 Public Overrides Function ToString() As String 54 Return MyBase.ToString() & "; Height = " & mHeight 55 End Function ' ToString ' override property Name from class CCircle3 58 Public Overrides ReadOnly Property Name() As String Get 61 Return "CCylinder3" 62 End Get End Property ' Name End Class ' CCylinder3 Calculates cylinder’s Area and Volume Returns the string CCylinder3

 2002 Prentice Hall. All rights reserved. Outline 58 Test3.vb 1 ' Fig : Test3.vb 2 ' Demonstrate polymorphism in Point-Circle-Cylinder hierarchy. 3 4 Imports System.Windows.Forms 5 6 Class CTest3 7 8 Shared Sub Main() 9 10 ' instantiate CPoint3, CCircle3 and CCylinder3 objects 11 Dim point As New CPoint3(7, 11) 12 Dim circle As New CCircle3(22, 8, 3.5) 13 Dim cylinder As New CCylinder3(10, 10, 3.3, 10) ' instantiate array of interface references 16 Dim arrayOfShapes As IShape() = New IShape(2){} ' arrayOfShapes(0) references CPoint3 object 19 arrayOfShapes(0) = point ' arrayOfShapes(1) references CCircle3 object 22 arrayOfShapes(1) = circle ' arrayOfShapes(2) references CCylinder3 object 25 arrayOfShapes(2) = cylinder Dim output As String = point.Name & ": " & _ 28 point.ToString() & vbCrLf & circle.Name & ": " & _ 29 circle.ToString() & vbCrLf & cylinder.Name & _ 30 ": " & cylinder.ToString() Dim shape As IShape 33 Declares arrayOfShapes as an array of IShape interface reference

 2002 Prentice Hall. All rights reserved. Outline 59 Test3.vb 34 ' display name, area and volume for each object in 35 ' arrayOfShapes 36 For Each shape In arrayOfShapes 37 output &= vbCrLf & vbCrLf & shape.Name & ": " & _ 38 vbCrLf & "Area = " & _ 39 String.Format("{0:F}", shape.Area) & vbCrLf & _ 40 "Volume = " & String.Format("{0:F}", shape.Volume) 41 Next MessageBox.Show(output, "Demonstrating Polymorphism") 44 End Sub ' Main End Class ' CTest3

 2002 Prentice Hall. All rights reserved Delegates Delegates –Classes that encapsulate a set of references to methods A delegate object that contains method references can be passed to another method –Singlecast delegates Delegates containing a single method and they are created and derived from class Delegate –Multicast delegates Delegates containing multiple methods and they are derived from class MulticastDelegate –AddressOf Creates a delegate instance enclosing a reference to that method

 2002 Prentice Hall. All rights reserved. Outline 61 DelegateBubbleSo rt.vb 1 ' Fig : DelegateBubbleSort.vb 2 ' Uses delegates to sort random numbers (ascending or descending). 3 4 Public Class CDelegateBubbleSort 5 6 ' delegate definition 7 Public Delegate Function Comparator( _ 8 ByVal element1 As Integer, _ 9 ByVal element2 As Integer) As Boolean ' sort array depending on comparator 12 Public Sub SortArray(ByVal array As Integer(), _ 13 ByVal Compare As Comparator) Dim i, pass As Integer For pass = 0 To array.GetUpperBound(0) ' comparison inner loop 20 For i = 0 To array.GetUpperBound(0) If Compare(array(i), array(i + 1)) Then 23 Swap(array(i), array(i + 1)) 24 End If Next ' inner loop Next ' outer loop End Sub ' SortArray ' swap two elements 33 Private Sub Swap(ByRef firstElement As Integer, _ 34 ByRef secondElement As Integer) 35 Declaration of a delegate ComparatorReturns value Boolean Define method SortArray Determines how to sort the array

 2002 Prentice Hall. All rights reserved. Outline 62 DelegateBubbleSo rt.vb 36 Dim hold As Integer hold = firstElement 39 firstElement = secondElement 40 secondElement = hold 41 End Sub ' Swap End Class ' CDelegateBubbleSort

 2002 Prentice Hall. All rights reserved. Outline 63 FrmBubbleSort.vb 1 ' Fig : FrmBubbleSort.vb 2 ' Create GUI that enables user to sort array. 3 4 Imports System.Windows.Forms 5 6 Public Class CFrmBubbleSort 7 Inherits Form 8 9 ' TextBox that contains original list 10 Friend WithEvents txtOriginal As TextBox 11 Friend WithEvents lblOriginal As Label ' TextBox that contains sorted list 14 Friend WithEvents txtSorted As TextBox 15 Friend WithEvents lblSorted As Label ' Buttons for creating and sorting lists 18 Friend WithEvents cmdCreate As Button 19 Friend WithEvents cmdSortAscending As Button 20 Friend WithEvents cmdSortDescending As Button ' Windows Form Designer generate code ' reference to object containing delegate 25 Dim mBubbleSort As New CDelegateBubbleSort() ' original array with unsorted elements 28 Dim mElementArray As Integer() = New Integer(9){} ' delegate implementation sorts in asending order 31 Private Function SortAscending(ByVal element1 As Integer, _ 32 ByVal element2 As Integer) As Boolean Return element1 > element2 35 End Function ' SortAscending Displays a list of unsorted numbersDisplays a list of sorted sequence Creates a list in either ascending or descending order Defines method SortAscending

 2002 Prentice Hall. All rights reserved. Outline 64 FrmBubbleSort.vb ' delegate implementation sorts in descending order 38 Private Function SortDescending(ByVal element1 As Integer, _ 39 ByVal element2 As Integer) As Boolean Return element1 < element2 42 End Function ' SortDescending ' creates random generated numbers 45 Private Sub cmdCreate_Click(ByVal sender As System.Object, _ 46 ByVal e As System.EventArgs) Handles cmdCreate.Click txtSorted.Clear() Dim output As String 51 Dim randomNumber As Random = New Random() 52 Dim i As Integer ' create String with 10 random numbers 55 For i = 0 To mElementArray.GetUpperBound(0) 56 mElementArray(i) = randomNumber.Next(100) 57 output &= mElementArray(i) & vbCrLf 58 Next txtOriginal.Text = output ' display numbers ' enable sort buttons 63 cmdSortAscending.Enabled = True 64 cmdSortDescending.Enabled = True 65 End Sub ' cmdCreate_Click 66 Defines method SortDescending

 2002 Prentice Hall. All rights reserved. Outline 65 FrmBubbleSort.vb 67 ' display array contents in specified TextBox 68 Private Sub DisplayResults() Dim output As String 71 Dim i As Integer ' create string with sorted numbers 74 For i = 0 To mElementArray.GetUpperBound(0) 75 output &= mElementArray(i) & vbCrLf 76 Next txtSorted.Text = output ' display numbers 79 End Sub ' DisplayResults ' sorts randomly generated numbers in ascending manner 82 Private Sub cmdSortAscending_Click(ByVal sender As _ 83 System.Object, ByVal e As System.EventArgs) _ 84 Handles cmdSortAscending.Click ' sort array 87 mBubbleSort.SortArray(mElementArray, AddressOf SortAscending) DisplayResults() ' display results cmdSortAscending.Enabled = False 92 cmdSortDescending.Enabled = True 93 End Sub ' cmdSortAscending_Click ' sorts randomly generated numbers in descending manner 96 Private Sub cmdSortDescending_Click(ByVal sender As _ 97 System.Object, ByVal e As System.EventArgs) _ 98 Handles cmdSortDescending.Click ' create sort object and sort array 101 mBubbleSort.SortArray(mElementArray, AddressOf SortDescending) Methods cmdSortAscending_Click and cmdSortDescending_Click are invoked when the user clicks the Sort Ascending and Sort Descending buttons

 2002 Prentice Hall. All rights reserved. Outline 66 FrmBubbleSort.vb DisplayResults() ' display results cmdSortDescending.Enabled = False 106 cmdSortAscending.Enabled = True 107 End Sub ' cmdSortDescending_Click End Class ' CFrmBubbleSort

 2002 Prentice Hall. All rights reserved. Outline 67 FrmBubbleSort.vb