Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: " 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."— Presentation transcript:

1  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 10.10 Delegates

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

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

4  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() 11 12 ' implicit call to Object constructor occurs here 13 X = 0 14 Y = 0 15 End Sub ' New 16 17 ' constructor 18 Public Sub New(ByVal xValue As Integer, _ 19 ByVal yValue As Integer) 20 21 ' implicit call to Object constructor occurs here 22 X = xValue 23 Y = yValue 24 End Sub ' New 25 26 ' property X 27 Public Property X() As Integer 28 29 Get 30 Return mX 31 End Get 32 33 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

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

6  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() 11 12 ' implicit call to CPoint constructor occurs here 13 Radius = 0 14 End Sub ' New 15 16 ' constructor 17 Public Sub New(ByVal xValue As Integer, _ 18 ByVal yValue As Integer, ByVal radiusValue As Double) 19 20 ' use MyBase reference to CPoint constructor explicitly 21 MyBase.New(xValue, yValue) 22 Radius = radiusValue 23 End Sub ' New 24 25 ' property Radius 26 Public Property Radius() As Double 27 28 Get 29 Return mRadius 30 End Get 31 32 Set(ByVal radiusValue As Double) 33 Class CCircle inherits class CPoint Sets Radius to 0 as a default value

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

8  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 13 14 point1 = New CPoint(30, 50) 15 circle1 = New CCircle(120, 89, 2.7) 16 17 output = "CPoint point1: " & point1.ToString() & _ 18 vbCrLf & "CCircle circle1: " & circle1.ToString() 19 20 ' use is-a relationship to assign CCircle to CPoint reference 21 point2 = circle1 22 23 output &= vbCrLf & vbCrLf & _ 24 "CCircle circle1 (via point2): " & point2.ToString() 25 26 ' downcast (cast base-class reference to derived-class 27 ' data type) point2 to circle2 28 circle2 = CType(point2, CCircle) ' allowed only via cast 29 30 output &= vbCrLf & vbCrLf & _ 31 "CCircle circle1 (via circle2): " & circle2.ToString() 32 33 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

9  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 44 45 MessageBox.Show(output, _ 46 "Demonstrating the 'is a' relationship") 47 End Sub ' Main 48 49 End Class ' CTest Improper case since point1 references a CPoint object

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

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

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

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

14  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 12 13 ' return shape volume 14 Public Overridable Function Volume() As Double 15 Return 0 16 End Function ' Volume 17 18 ' overridable method that should return shape name 19 Public MustOverride ReadOnly Property Name() As String 20 21 End Class ' CShape Class CShape declared as MustInherit or abstract Keyword Overridable must accompany every method in MustInherit class

15  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() 12 13 ' implicit call to Object constructor occurs here 14 X = 0 15 Y = 0 16 End Sub ' New 17 18 ' constructor 19 Public Sub New(ByVal xValue As Integer, _ 20 ByVal yValue As Integer) 21 22 ' implicit call to Object constructor occurs here 23 X = xValue 24 Y = yValue 25 End Sub ' New 26 27 ' property X 28 Public Property X() As Integer 29 30 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

16  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 37 38 End Property ' X 39 40 ' property Y 41 Public Property Y() As Integer 42 43 Get 44 Return mY 45 End Get 46 47 Set(ByVal yValue As Integer) 48 mY = yValue ' no need for validation 49 End Set 50 51 End Property ' Y 52 53 ' return String representation of CPoint2 54 Public Overrides Function ToString() As String 55 Return "[" & mX & ", " & mY & "]" 56 End Function ' ToString 57 58 ' implement MustOverride property of class CShape 59 Public Overrides ReadOnly Property Name() As String 60 61 Get 62 Return "CPoint2" 63 End Get 64 65 End Property ' Name 66 67 End Class ' CPoint2 Class CPoint2 implements property Name

17  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() 11 12 ' implicit call to CPoint2 constructor occurs here 13 Radius = 0 14 End Sub ' New 15 16 ' constructor 17 Public Sub New(ByVal xValue As Integer, _ 18 ByVal yValue As Integer, ByVal radiusValue As Double) 19 20 ' use MyBase reference to CPoint2 constructor explicitly 21 MyBase.New(xValue, yValue) 22 Radius = radiusValue 23 End Sub ' New 24 25 ' property Radius 26 Public Property Radius() As Double 27 28 Get 29 Return mRadius 30 End Get 31 32 Set(ByVal radiusValue As Double) 33 34 If radiusValue >= 0 ' mRadius must be nonnegative 35 mRadius = radiusValue Class CCircle2 inherits from class CPoint2 Class CCircle2 provides member variable mRadius Property Radius

18  2002 Prentice Hall. All rights reserved. Outline 18 Circle2.vb 36 End If 37 38 End Set 39 40 End Property ' Radius 41 42 ' calculate CCircle2 diameter 43 Public Function Diameter() As Double 44 Return mRadius * 2 45 End Function ' Diameter 46 47 ' calculate CCircle2 circumference 48 Public Function Circumference() As Double 49 Return Math.PI * Diameter() 50 End Function ' Circumference 51 52 ' calculate CCircle2 area 53 Public Overrides Function Area() As Double 54 Return Math.PI * mRadius ^ 2 55 End Function ' Area 56 57 ' return String representation of CCircle2 58 Public Overrides Function ToString() As String 59 60 ' use MyBase to return CCircle2 String representation 61 Return "Center = " & MyBase.ToString() & _ 62 "; Radius = " & mRadius 63 End Function ' ToString 64 65 ' override property Name from class CPoint2 66 Public Overrides ReadOnly Property Name() As String 67 68 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

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

20  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() 11 12 ' implicit call to CCircle2 constructor occurs here 13 Height = 0 14 End Sub ' New 15 16 ' 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) 20 21 ' explicit call to CCircle2 constructor 22 MyBase.New(xValue, yValue, radiusValue) 23 Height = heightValue ' set CCylinder2 height 24 End Sub ' New 25 26 ' property Height 27 Public Property Height() As Double 28 29 Get 30 Return mHeight 31 End Get 32 33 ' 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

21  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 39 40 End Set 41 42 End Property ' Height 43 44 ' 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 48 49 ' calculate CCylinder2 volume 50 Public Overrides Function Volume() As Double 51 Return MyBase.Area * mHeight 52 End Function ' Volume 53 54 ' convert CCylinder2 to String 55 Public Overrides Function ToString() As String 56 Return MyBase.ToString() & "; Height = " & mHeight 57 End Function ' ToString 58 59 ' override property Name from class CCircle2 60 Public Overrides ReadOnly Property Name() As String 61 62 Get 63 Return "CCylinder2" 64 End Get 65 66 End Property ' Name 67 68 End Class ' CCylinder2 Overrides methods Area, Volume and ToString Defines function Name as ReadOnly and overridable that returns name CCylinder

22  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) 14 15 ' instantiate array of base-class references 16 Dim arrayOfShapes As CShape() = New CShape(2){} 17 18 ' arrayOfShapes(0) refers to CPoint2 object 19 arrayOfShapes(0) = point 20 21 ' arrayOfShapes(1) refers to CCircle2 object 22 arrayOfShapes(1) = circle 23 24 ' arrayOfShapes(2) refers to CCylinder2 object 25 arrayOfShapes(2) = cylinder 26 27 Dim output As String = point.Name & ": " & _ 28 point.ToString() & vbCrLf & circle.Name & ": " & _ 29 circle.ToString() & vbCrLf & cylinder.Name & _ 30 ": " & cylinder.ToString() 31 32 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

23  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 42 43 MessageBox.Show(output, "Demonstrating Polymorphism") 44 End Sub ' Main 45 46 End Class ' CTest2 Uses base-class CShape references to invoke each derived-class object’s methods and properties

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

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

26  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) 12 13 FirstName = firstNameValue 14 LastName = lastNameValue 15 End Sub ' New 16 17 ' property FirstName 18 Public Property FirstName() As String 19 20 Get 21 Return mFirstName 22 End Get 23 24 Set(ByVal firstNameValue As String) 25 mFirstName = firstNameValue 26 End Set 27 28 End Property ' FirstName 29 30 ' property LastName 31 Public Property LastName() As String 32 33 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

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

28  2002 Prentice Hall. All rights reserved. Outline 28 Boss.vb 1 ' Fig. 10.10: 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) 12 13 MyBase.New(firstNameValue, lastNameValue) 14 WeeklySalary = salaryValue 15 End Sub ' New 16 17 ' property WeeklySalary 18 Public Property WeeklySalary() As Decimal 19 20 Get 21 Return mSalary 22 End Get 23 24 Set(ByVal bossSalaryValue As Decimal) 25 26 ' validate mSalary 27 If bossSalaryValue > 0 28 mSalary = bossSalaryValue 29 End If 30 31 End Set 32 33 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

29  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 39 40 ' return Boss' name 41 Public Overrides Function ToString() As String 42 Return "CBoss: " & MyBase.ToString() 43 End Function ' ToString 44 45 End Class ' CBoss Defines method Earnings Returns a string indicating the type of employee

30  2002 Prentice Hall. All rights reserved. Outline 30 CommissionWorker.vb 1 ' Fig. 10.11: 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 10 11 ' 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) 16 17 MyBase.New(firstNameValue, lastNameValue) 18 Salary = salaryValue 19 Commission = commissionValue 20 Quantity = quantityValue 21 End Sub ' New 22 23 ' property Salary 24 Public Property Salary() As Decimal 25 26 Get 27 Return mSalary 28 End Get 29 30 Set(ByVal salaryValue As Decimal) 31 32 ' 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

31  2002 Prentice Hall. All rights reserved. Outline 31 CommissionWorker.vb 36 37 End Set 38 39 End Property ' Salary 40 41 ' property Commission 42 Public Property Commission() As Decimal 43 44 Get 45 Return mCommission 46 End Get 47 48 Set(ByVal commissionValue As Decimal) 49 50 ' validate mCommission 51 If commissionValue > 0 Then 52 mCommission = commissionValue 53 End If 54 55 End Set 56 57 End Property ' Commission 58 59 ' property Quantity 60 Public Property Quantity() As Integer 61 62 Get 63 Return mQuantity 64 End Get 65 66 Set(ByVal QuantityValue As Integer) 67 Ensures CommisionValue is positive

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

33  2002 Prentice Hall. All rights reserved. Outline 33 PieceWorker.vb 1 ' Fig. 10.12: 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) 15 16 MyBase.New(firstNameValue, lastNameValue) 17 WagePerPiece = wagePerPieceValue 18 Quantity = quantityValue 19 End Sub ' New 20 21 ' property WagePerPiece 22 Public Property WagePerPiece() As Decimal 23 24 Get 25 Return mAmountPerPiece 26 End Get 27 28 Set(ByVal wagePerPieceValue As Decimal) 29 30 ' validate mAmountPerPiece 31 If wagePerPieceValue > 0 Then 32 mAmountPerPiece = wagePerPieceValue 33 End If 34 35 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

34  2002 Prentice Hall. All rights reserved. Outline 34 PieceWorker.vb 36 37 End Property ' WagePerPiece 38 39 ' property Quantity 40 Public Property Quantity() As Integer 41 42 Get 43 Return mQuantity 44 End Get 45 46 Set(ByVal quantityValue As Integer) 47 48 ' validate mQuantity 49 If quantityValue > 0 Then 50 mQuantity = quantityValue 51 End If 52 53 End Set 54 55 End Property ' Quantity 56 57 ' override base-class method to calculate PieceWorker's earnings 58 Public Overrides Function Earnings() As Decimal 59 Return Quantity * WagePerPiece 60 End Function ' Earnings 61 62 ' return piece worker's name 63 Public Overrides Function ToString() As String 64 Return "CPieceWorker: " & MyBase.ToString() 65 End Function ' ToString 66 67 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

35  2002 Prentice Hall. All rights reserved. Outline 35 HourlyWorker.vb 1 ' Fig. 10.13: 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) 14 15 MyBase.New(firstNameValue, lastNameValue) 16 HourlyWage = wageValue 17 Hours = hourValue 18 End Sub ' New 19 20 ' property HourlyWage 21 Public Property HourlyWage() As Decimal 22 23 Get 24 Return mWage 25 End Get 26 27 Set(ByVal hourlyWageValue As Decimal) 28 29 ' validate mWage 30 If hourlyWageValue > 0 Then 31 mWage = hourlyWageValue 32 End If 33 34 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

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

37  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 73 74 End Class ' CHourlyWorker Method ToString returns a string indicating the type of employee

38  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 11 12 Dim boss As CBoss = New CBoss("John", "Smith", 800) 13 14 Dim commissionWorker As CCommissionWorker = _ 15 New CCommissionWorker("Sue", "Jones", 400, 3, 150) 16 17 Dim pieceWorker As CPieceWorker = _ 18 New CPieceWorker("Bob", "Lewis", _ 19 Convert.ToDecimal(2.5), 200) 20 21 Dim hourlyWorker As CHourlyWorker = _ 22 New CHourlyWorker("Karen", "Price", _ 23 Convert.ToDecimal(13.75), 40) 24 25 ' employee reference to a CBoss 26 employee = boss 27 output &= GetString(employee) & boss.ToString() & _ 28 " earned " & boss.Earnings.ToString("C") & vbCrLf & vbCrLf 29 30 ' 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

39  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 41 42 ' employee reference to a CHourlyWorker 43 employee = hourlyWorker 44 output &= GetString(employee) & _ 45 hourlyWorker.ToString() & " earned " & _ 46 hourlyWorker.Earnings.ToString("C") & vbCrLf & vbCrLf 47 48 MessageBox.Show(output, "Demonstrating Polymorphism", _ 49 MessageBoxButtons.OK, MessageBoxIcon.Information) 50 End Sub ' Main 51 52 ' 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 57 58 End Class ' CTest Invokes CBoss method Earnings Invokes CBoss method ToString Assigns the derived-class reference pieceWorker to the base-class CEmployee reference employee

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

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

42  2002 Prentice Hall. All rights reserved. Outline 42 IAge.vb 1 ' Fig. 10.15: 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

43  2002 Prentice Hall. All rights reserved. Outline 43 Person.vb 1 ' Fig. 10.16: 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 10 11 ' 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) 15 16 ' implicit call to Object constructor 17 mFirstName = firstNameValue 18 mLastName = lastNameValue 19 20 ' validate year 21 If (yearBornValue > 0 AndAlso _ 22 yearBornValue <= Date.Now.Year) 23 24 mYearBorn = yearBornValue 25 Else 26 mYearBorn = Date.Now.Year 27 End If 28 29 End Sub ' New 30 31 ' 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

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

45  2002 Prentice Hall. All rights reserved. Outline 45 Tree.vb 1 ' Fig. 10.17: 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) 11 12 ' implicit call to Object constructor 13 mRings = Date.Now.Year - yearPlanted 14 End Sub ' New 15 16 ' increment mRings 17 Public Sub AddRing() 18 mRings += 1 19 End Sub ' AddRing 20 21 ' property Age 22 ReadOnly Property Age() As Integer _ 23 Implements IAge.Age 24 25 Get 26 Return mRings 27 End Get 28 29 End Property ' Age 30 31 ' 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

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

47  2002 Prentice Hall. All rights reserved. Outline 47 Test.vb 1 ' Fig. 10.18: 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) 13 14 ' instantiate array of interface references 15 Dim iAgeArray As IAge() = New IAge(1){} 16 17 ' iAgeArray(0) references CTree object 18 iAgeArray(0) = tree 19 20 ' iAgeArray(1) references CPerson object 21 iAgeArray(1) = person 22 23 ' display tree information 24 Dim output As String = tree.ToString() & ": " & _ 25 tree.Name & vbCrLf & "Age is " & tree.Age & vbCrLf & _ 26 vbCrLf 27 28 ' display person information 29 output &= person.ToString() & ": " & _ 30 person.Name & vbCrLf & "Age is " & person.Age & _ 31 vbCrLf 32 33 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

48  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 40 41 MessageBox.Show(output, "Demonstrating Polymorphism") 42 End Sub ' Main 43 44 End Class ' CTest Defines For Each structure

49  2002 Prentice Hall. All rights reserved. Outline 49 Shape.vb 1 ' Fig. 10.19: 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 10 11 End Interface ' IShape Defines interface IShapeSpecifies two methods and one property Name

50  2002 Prentice Hall. All rights reserved. Outline 50 Point3.vb 1 ' Fig. 10.20: 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 15 16 ' constructor 17 Public Sub New(ByVal xValue As Integer, _ 18 ByVal yValue As Integer) 19 X = xValue 20 Y = yValue 21 End Sub ' New 22 23 ' property X 24 Public Property X() As Integer 25 26 Get 27 Return mX 28 End Get 29 30 Set(ByVal xValue As Integer) 31 mX = xValue ' no need for validation 32 End Set 33 34 End Property ' X 35 Class Cpoint3 implements interface IShape Declares two Private integers mX and mY Property X

51  2002 Prentice Hall. All rights reserved. Outline 51 Point3.vb 36 ' property Y 37 Public Property Y() As Integer 38 39 Get 40 Return mY 41 End Get 42 43 Set(ByVal yValue As Integer) 44 mY = yValue ' no need for validation 45 End Set 46 47 End Property ' Y 48 49 ' return String representation of CPoint3 50 Public Overrides Function ToString() As String 51 Return "[" & mX & ", " & mY & "]" 52 End Function ' ToString 53 54 ' implement interface IShape method Area 55 Public Overridable Function Area() As Double _ 56 Implements IShape.Area 57 58 Return 0 59 End Function ' Area 60 61 ' implement interface IShape method Volume 62 Public Overridable Function Volume() As Double _ 63 Implements IShape.Volume 64 65 Return 0 66 End Function ' Volume 67 68 ' 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

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

53  2002 Prentice Hall. All rights reserved. Outline 53 Circle3.vb 1 ' Fig. 10.21: 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 13 14 ' constructor 15 Public Sub New(ByVal xValue As Integer, _ 16 ByVal yValue As Integer, ByVal radiusValue As Double) 17 18 ' use MyBase reference to CPoint constructor explicitly 19 MyBase.New(xValue, yValue) 20 Radius = radiusValue 21 End Sub ' New 22 23 ' property Radius 24 Public Property Radius() As Double 25 26 Get 27 Return mRadius 28 End Get 29 30 Set(ByVal radiusValue As Double) 31 32 If radiusValue >= 0 33 mRadius = radiusValue ' mRadius cannot be negative 34 End If 35 Class CCircle3 inherits CPoint3 Declares Private member variable mRadius

54  2002 Prentice Hall. All rights reserved. Outline 54 Circle3.vb 36 End Set 37 38 End Property ' Radius 39 40 ' calculate CCircle3 diameter 41 Public Function Diameter() As Double 42 Return mRadius * 2 43 End Function ' Diameter 44 45 ' calculate CCircle3 circumference 46 Public Function Circumference() As Double 47 Return Math.PI * Diameter() 48 End Function ' Circumference 49 50 ' calculate CCircle3 area 51 Public Overrides Function Area() As Double 52 Return Math.PI * mRadius ^ 2 53 End Function ' Area 54 55 ' override interface IShape property Name from class CPoint3 56 Public ReadOnly Overrides Property Name() As String 57 58 Get 59 Return "CCircle3" 60 End Get 61 62 End Property ' Name 63 64 ' return String representation of CCircle3 65 Public Overrides Function ToString() As String 66 67 ' 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

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

56  2002 Prentice Hall. All rights reserved. Outline 56 Cylinder3.vb 1 ' Fig. 10.22: 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 13 14 ' 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) 18 19 ' explicit call to CCircle2 constructor 20 MyBase.New(xValue, yValue, radiusValue) 21 Height = heightValue ' set CCylinder2 height 22 End Sub ' New 23 24 ' property Height 25 Public Property Height() As Double 26 27 Get 28 Return mHeight 29 End Get 30 31 ' set CCylinder3 height if argument value is positive 32 Set(ByVal heightValue As Double) 33 34 If heightValue >= 0 Then 35 mHeight = heightValue Class CCylinder3 inherits from class CCircle3

57  2002 Prentice Hall. All rights reserved. Outline 57 Cylinder3.vb 36 End If 37 38 End Set 39 40 End Property ' Height 41 42 ' 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 46 47 ' calculate CCylinder3 volume 48 Public Overrides Function Volume() As Double 49 Return MyBase.Area * mHeight 50 End Function ' Volume 51 52 ' convert CCylinder3 to String 53 Public Overrides Function ToString() As String 54 Return MyBase.ToString() & "; Height = " & mHeight 55 End Function ' ToString 56 57 ' override property Name from class CCircle3 58 Public Overrides ReadOnly Property Name() As String 59 60 Get 61 Return "CCylinder3" 62 End Get 63 64 End Property ' Name 65 66 End Class ' CCylinder3 Calculates cylinder’s Area and Volume Returns the string CCylinder3

58  2002 Prentice Hall. All rights reserved. Outline 58 Test3.vb 1 ' Fig. 10.23: 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) 14 15 ' instantiate array of interface references 16 Dim arrayOfShapes As IShape() = New IShape(2){} 17 18 ' arrayOfShapes(0) references CPoint3 object 19 arrayOfShapes(0) = point 20 21 ' arrayOfShapes(1) references CCircle3 object 22 arrayOfShapes(1) = circle 23 24 ' arrayOfShapes(2) references CCylinder3 object 25 arrayOfShapes(2) = cylinder 26 27 Dim output As String = point.Name & ": " & _ 28 point.ToString() & vbCrLf & circle.Name & ": " & _ 29 circle.ToString() & vbCrLf & cylinder.Name & _ 30 ": " & cylinder.ToString() 31 32 Dim shape As IShape 33 Declares arrayOfShapes as an array of IShape interface reference

59  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 42 43 MessageBox.Show(output, "Demonstrating Polymorphism") 44 End Sub ' Main 45 46 End Class ' CTest3

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

61  2002 Prentice Hall. All rights reserved. Outline 61 DelegateBubbleSo rt.vb 1 ' Fig. 10.24: 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 10 11 ' sort array depending on comparator 12 Public Sub SortArray(ByVal array As Integer(), _ 13 ByVal Compare As Comparator) 14 15 Dim i, pass As Integer 16 17 For pass = 0 To array.GetUpperBound(0) 18 19 ' comparison inner loop 20 For i = 0 To array.GetUpperBound(0) - 1 21 22 If Compare(array(i), array(i + 1)) Then 23 Swap(array(i), array(i + 1)) 24 End If 25 26 Next ' inner loop 27 28 Next ' outer loop 29 30 End Sub ' SortArray 31 32 ' 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

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

63  2002 Prentice Hall. All rights reserved. Outline 63 FrmBubbleSort.vb 1 ' Fig. 10.25: 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 12 13 ' TextBox that contains sorted list 14 Friend WithEvents txtSorted As TextBox 15 Friend WithEvents lblSorted As Label 16 17 ' Buttons for creating and sorting lists 18 Friend WithEvents cmdCreate As Button 19 Friend WithEvents cmdSortAscending As Button 20 Friend WithEvents cmdSortDescending As Button 21 22 ' Windows Form Designer generate code 23 24 ' reference to object containing delegate 25 Dim mBubbleSort As New CDelegateBubbleSort() 26 27 ' original array with unsorted elements 28 Dim mElementArray As Integer() = New Integer(9){} 29 30 ' delegate implementation sorts in asending order 31 Private Function SortAscending(ByVal element1 As Integer, _ 32 ByVal element2 As Integer) As Boolean 33 34 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

64  2002 Prentice Hall. All rights reserved. Outline 64 FrmBubbleSort.vb 36 37 ' delegate implementation sorts in descending order 38 Private Function SortDescending(ByVal element1 As Integer, _ 39 ByVal element2 As Integer) As Boolean 40 41 Return element1 < element2 42 End Function ' SortDescending 43 44 ' creates random generated numbers 45 Private Sub cmdCreate_Click(ByVal sender As System.Object, _ 46 ByVal e As System.EventArgs) Handles cmdCreate.Click 47 48 txtSorted.Clear() 49 50 Dim output As String 51 Dim randomNumber As Random = New Random() 52 Dim i As Integer 53 54 ' 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 59 60 txtOriginal.Text = output ' display numbers 61 62 ' enable sort buttons 63 cmdSortAscending.Enabled = True 64 cmdSortDescending.Enabled = True 65 End Sub ' cmdCreate_Click 66 Defines method SortDescending

65  2002 Prentice Hall. All rights reserved. Outline 65 FrmBubbleSort.vb 67 ' display array contents in specified TextBox 68 Private Sub DisplayResults() 69 70 Dim output As String 71 Dim i As Integer 72 73 ' create string with sorted numbers 74 For i = 0 To mElementArray.GetUpperBound(0) 75 output &= mElementArray(i) & vbCrLf 76 Next 77 78 txtSorted.Text = output ' display numbers 79 End Sub ' DisplayResults 80 81 ' 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 85 86 ' sort array 87 mBubbleSort.SortArray(mElementArray, AddressOf SortAscending) 88 89 DisplayResults() ' display results 90 91 cmdSortAscending.Enabled = False 92 cmdSortDescending.Enabled = True 93 End Sub ' cmdSortAscending_Click 94 95 ' 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 99 100 ' 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

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

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


Download ppt " 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."

Similar presentations


Ads by Google