1 / 67

Chapter 10 – Object-Oriented Programming: Part 2

Chapter 10 – Object-Oriented Programming: Part 2.

mariah
Télécharger la présentation

Chapter 10 – Object-Oriented Programming: Part 2

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 10 – Object-Oriented Programming: Part 2 Outline10.1 Introduction10.2   Derived-Class-Object to Base-Class-Object Conversion10.3   Type Fields and SelectCase Statements10.4   Polymorphism Examples10.5   Abstract Classes and Methods10.6   Case Study: Inheriting Interface and Implementation10.7   NotInheritable Classes and NotOverridable Methods10.8   Case Study: Payroll System Using Polymorphism10.9   Case Study: Creating and Using Interfaces10.10   Delegates

  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. 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. Declares integer variables mX and mY as Private Sets X and Y to zero Sets xValue and yValue to X and Y 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 Point.vb

  5. Method ToString declared as overridable 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 Point.vb

  6. Class CCircle inherits class CPoint Sets Radius to 0 as a default value 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 Circle.vb

  7. Ensures radiusValue is greater or equal to zero Methods to calculate Diameter, Circumference, Area and ToString 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 Circle.vb

  8. Assign a new CPoint object to point1 Declares two CPoint References Declares two CCircle References 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 CCircleobject to which CCircle2 refers to 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 Test.vb

  9. Improper case since point1 references a CPoint object 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 Test.vb

  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. 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. 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. 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 CShapeand overrides property Name • Class CCircle2 • Inherits from class CPoint2 • Overrides method Area, andproperty Name • Class CCylinder2 • Inherits from class CCircle2 • Overrides method Area, defines method Volume and Specifies property Name

  14. Class CShape declared as MustInherit or abstract Keyword Overridable must accompany every method in MustInherit class 1 ' Fig. 10.4: Shape.vb 2 ' Demonstrate a shape hierarchy using MustInherit class. 3 4 Imports System.Windows.Forms 5 6 PublicMustInheritClass CShape 7 8 ' return shape area 9 PublicOverridableFunction Area() AsDouble 10 Return0 11 EndFunction ' Area 12 13 ' return shape volume 14 PublicOverridableFunction Volume() AsDouble 15 Return0 16 EndFunction ' Volume 17 18 ' overridable method that should return shape name 19 PublicMustOverrideReadOnlyProperty Name() AsString 20 21 EndClass' CShape Shape.vb

  15. Class CPoint2 inherits class CShape Class CPoint2 provides member variables mX and mY Sets both variables to zero 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 Point2.vb

  16. Class CPoint2 implements property Name 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 PublicOverridesReadOnlyProperty Name() AsString 60 61 Get 62 Return"CPoint2" 63 EndGet 64 65 End Property ' Name 66 67 End Class ' CPoint2 Point2.vb

  17. Class CCircle2 inherits from class CPoint2 Class CCircle2 provides member variable mRadius Property Radius 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 Circle2.vb

  18. Method to calculate Diameter and Circumference Method Area declared as overridable Defines function ToString as overridable Defines function Name as ReadOnly and overridable that returns name CCircle2 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 PublicOverridesReadOnlyProperty Name() AsString 67 68 Get 69 Return"CCircle2" 70 End Get Circle2.vb

  19. 71 72 End Property ' Name 73 74 End Class ' CCircle2 Circle2.vb

  20. Class CCylinder2 inherits class CCircle2 Class CCylinder2 contains a member variable mHeight Property Height 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 Cylinder2.vb

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

  22. Declares CPoint2 object point,CCircle2 object circle, and CCylinder2 object cylinder Declares an array arrayOfShapes which contains three CShape references Invokes property Name and method ToString for each object Assigns reference Circle to array element arrayOfShapes(1) Uses derived-class references to invoke each derived-class object’s methods and properties 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 SharedSubMain() 9 10 ' instantiate CPoint2, CCircle2 and CCylinder2 objects 11 Dim point AsNew CPoint2(7, 11) 12 Dim circle AsNew CCircle2(22, 8, 3.5) 13 Dim cylinder AsNew 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 AsString = point.Name & ": " & _ 28 point.ToString() & vbCrLf & circle.Name & ": " & _ 29 circle.ToString() & vbCrLf & cylinder.Name & _ 30 ": " & cylinder.ToString() 31 32 Dim shape As CShape 33 Test2.vb

  23. Uses base-class CShape references to invoke each derived-class object’s methods and properties 34 ' display name, area and volume for each object in 35 ' arrayOfShapes polymorphically 36 ForEach 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 Test2.vb

  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. 10.8 Case Study: Payroll System Using Polymorphism • Class CEmployee • Derived classes of CEmployee are CCommisionerWorker, CPieceWorker and CHourlyWorker • Ifclasses 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. Declares two Private variables mFirstName and mLastNameas strings Keyword MustInherit indicates that class CEmployee is abstract Takes two arguments firstNameValueand lastNameValue Property FirstNameand LastName 1 ' Fig. 10.9: Employee.vb 2 ' Abstract base class for employee derived classes. 3 4 PublicMustInheritClass CEmployee 5 6 Private mFirstName AsString 7 Private mLastName AsString 8 9 ' constructor 10 PublicSubNew(ByVal firstNameValue AsString, _ 11 ByVal lastNameValue AsString) 12 13 FirstName = firstNameValue 14 LastName = lastNameValue 15 End Sub ' New 16 17 ' property FirstName 18 PublicProperty FirstName() AsString 19 20 Get 21 Return mFirstName 22 End Get 23 24 Set(ByVal firstNameValue AsString) 25 mFirstName = firstNameValue 26 End Set 27 28 End Property ' FirstName 29 30 ' property LastName 31 PublicProperty LastName() AsString 32 33 Get 34 Return mLastName 35 End Get Employee.vb

  27. Keyword MustOverride is attached to method Earnings 36 37 Set(ByVal lastNameValue AsString) 38 mLastName = lastNameValue 39 End Set 40 41 End Property ' LastName 42 43 ' obtain String representation of employee 44 PublicOverridesFunction ToString() AsString 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 PublicMustOverrideFunction Earnings() AsDecimal 51 52 EndClass' CEmployee Employee.vb

  28. NotInheritable class CBoss inheritsCEmloyee Class CBoss’s constructorreceives 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 1 ' Fig. 10.10: Boss.vb 2 ' Boss class derived from CEmployee. 3 4 PublicNotInheritableClass CBoss 5 Inherits CEmployee 6 7 Private mSalary AsDecimal 8 9 ' constructor for class CBoss 10 PublicSubNew(ByVal firstNameValue AsString, _ 11 ByVal lastNameValue AsString, ByVal salaryValue AsDecimal) 12 13 MyBase.New(firstNameValue, lastNameValue) 14 WeeklySalary = salaryValue 15 EndSub ' New 16 17 ' property WeeklySalary 18 PublicProperty WeeklySalary() AsDecimal 19 20 Get 21 Return mSalary 22 EndGet 23 24 Set(ByVal bossSalaryValue AsDecimal) 25 26 ' validate mSalary 27 If bossSalaryValue > 0 28 mSalary = bossSalaryValue 29 End If 30 31 End Set 32 33 End Property ' WeeklySalary 34 Boss.vb

  29. Defines method Earnings Returns a string indicating the type of employee 35 ' override base-class method to calculate Boss earnings 36 PublicOverridesFunction Earnings() AsDecimal 37 Return WeeklySalary 38 EndFunction ' Earnings 39 40 ' return Boss' name 41 PublicOverridesFunction ToString() AsString 42 Return"CBoss: " & MyBase.ToString() 43 End Function ' ToString 44 45 End Class' CBoss Boss.vb

  30. 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 1 ' Fig. 10.11: CommissionWorker.vb 2 ' CEmployee implementation for a commission worker. 3 4 PublicNotInheritableClass CCommissionWorker 5 Inherits CEmployee 6 7 Private mSalary AsDecimal' base salary per week 8 Private mCommission AsDecimal' amount per item sold 9 Private mQuantity AsInteger' total items sold 10 11 ' constructor for class CCommissionWorker 12 PublicSubNew(ByVal firstNameValue AsString, _ 13 ByVal lastNameValue AsString, ByVal salaryValue AsDecimal, _ 14 ByVal commissionValue AsDecimal, _ 15 ByVal quantityValue AsInteger) 16 17 MyBase.New(firstNameValue, lastNameValue) 18 Salary = salaryValue 19 Commission = commissionValue 20 Quantity = quantityValue 21 End Sub ' New 22 23 ' property Salary 24 PublicProperty Salary() AsDecimal 25 26 Get 27 Return mSalary 28 End Get 29 30 Set(ByVal salaryValue AsDecimal) 31 32 ' validate mSalary 33 If salaryValue > 0Then 34 mSalary = salaryValue 35 End If CommissionWorker.vb

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

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

  33. 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 1 ' Fig. 10.12: PieceWorker.vb 2 ' CPieceWorker class derived from CEmployee. 3 4 PublicNotInheritableClass CPieceWorker 5 Inherits CEmployee 6 7 Private mAmountPerPiece AsDecimal' wage per piece output 8 Private mQuantity AsInteger' output per week 9 10 ' constructor for CPieceWorker 11 PublicSubNew(ByVal firstNameValue AsString, _ 12 ByVal lastNameValue AsString, _ 13 ByVal wagePerPieceValue AsDecimal, _ 14 ByVal quantityValue AsInteger) 15 16 MyBase.New(firstNameValue, lastNameValue) 17 WagePerPiece = wagePerPieceValue 18 Quantity = quantityValue 19 End Sub ' New 20 21 ' property WagePerPiece 22 PublicProperty WagePerPiece() AsDecimal 23 24 Get 25 Return mAmountPerPiece 26 EndGet 27 28 Set(ByVal wagePerPieceValue AsDecimal) 29 30 ' validate mAmountPerPiece 31 If wagePerPieceValue > 0Then 32 mAmountPerPiece = wagePerPieceValue 33 EndIf 34 35 End Set PieceWorker.vb

  34. Validates that quantityValue is greater than 0 Method Earnings calculates a piece worker’s earnings Method ToString returns a string indicating the type of employee 36 37 End Property ' WagePerPiece 38 39 ' property Quantity 40 PublicProperty Quantity() AsInteger 41 42 Get 43 Return mQuantity 44 End Get 45 46 Set(ByVal quantityValue AsInteger) 47 48 ' validate mQuantity 49 If quantityValue > 0Then 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 PublicOverridesFunction Earnings() AsDecimal 59 Return Quantity * WagePerPiece 60 End Function ' Earnings 61 62 ' return piece worker's name 63 PublicOverridesFunction ToString() AsString 64 Return"CPieceWorker: " & MyBase.ToString() 65 End Function ' ToString 66 67 EndClass ' CPieceWorker PieceWorker.vb

  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 hourlyWageValueis greater than zero 1 ' Fig. 10.13: HourlyWorker.vb 2 ' CEmployee implementation for an hourly worker. 3 4 PublicNotInheritableClass CHourlyWorker 5 Inherits CEmployee 6 7 Private mWage AsDecimal' wage per hour 8 Private mHoursWorked AsDouble' hours worked for week 9 10 ' constructor for class CHourlyWorker 11 PublicSubNew(ByVal firstNameValue AsString, _ 12 ByVal lastNameValue AsString, _ 13 ByVal wageValue AsDecimal, ByVal hourValue AsDouble) 14 15 MyBase.New(firstNameValue, lastNameValue) 16 HourlyWage = wageValue 17 Hours = hourValue 18 EndSub ' New 19 20 ' property HourlyWage 21 PublicProperty HourlyWage() AsDecimal 22 23 Get 24 Return mWage 25 EndGet 26 27 Set(ByVal hourlyWageValue AsDecimal) 28 29 ' validate mWage 30 If hourlyWageValue > 0Then 31 mWage = hourlyWageValue 32 End If 33 34 End Set 35 HourlyWorker.vb

  36. Validates that hourValue is greater than zero Defines method Earnings 36 End Property ' HourlyWage 37 38 ' property Hours 39 PublicProperty Hours() AsDouble 40 41 Get 42 Return mHoursWorked 43 EndGet 44 45 Set(ByVal hourValue AsDouble) 46 47 ' validate mHoursWorked 48 If hourValue > 0Then 49 mHoursWorked = hourValue 50 EndIf 51 52 End Set 53 54 End Property ' Hours 55 56 ' override base-class method to calculate HourlyWorker earnings 57 PublicOverridesFunction Earnings() AsDecimal 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 HourlyWorker.vb

  37. Method ToString returns a string indicating the type of employee 69 ' return hourly worker's name 70 PublicOverridesFunction ToString() AsString 71 Return"CHourlyWorker: " & MyBase.ToString() 72 End Function ' ToString 73 74 EndClass' CHourlyWorker HourlyWorker.vb

  38. 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 toPrivate method GetString 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 SharedSub Main() 9 Dim employee As CEmployee ' base-class reference 10 Dim output AsString 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 Test.vb

  39. Assigns the derived-class reference pieceWorker to the base-class CEmployee reference employee Invokes CBoss method ToString Invokes CBoss method Earnings 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 EndSub' Main 51 52 ' return String containing employee information 53 SharedFunction GetString(ByVal worker As CEmployee) AsString 54 Return worker.ToString() & " earned " & _ 55 worker.Earnings.ToString("C") & vbCrLf 56 End Function ' GetString 57 58 EndClass' CTest Test.vb

  40. Test.vb

  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. Definition of interface IAge Specify properties Age and Name 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 IAge.vb

  43. 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 1 ' Fig. 10.16: Person.vb 2 ' Class CPerson has a birthday. 3 4 Public Class CPerson 5 Implements IAge 6 7 Private mYearBorn AsInteger 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 AsInteger) 15 16 ' implicit call to Object constructor 17 mFirstName = firstNameValue 18 mLastName = lastNameValue 19 20 ' validate year 21 If (yearBornValue > 0AndAlso _ 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 Person.vb

  44. 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 Person.vb Definition of Name

  45. Class CTree implements interface IAge Class CTree contains member variables mRings CTree constructor takesone argument Class CTree includes method AddRing Definition of Age and Name 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 EndGet 28 29 End Property' Age 30 31 ' property Name implementation of interface IAge 32 ReadOnly Property Name() As String _ 33 Implements IAge.Name 34 Tree.vb

  46. 35 Get 36 Return"Tree" 37 End Get 38 39 End Property' Name 40 41 End Class' CTree Tree.vb

  47. Instantiates object tree of class CTree Declares object person of class CPerson Declares IAgeArray of two references to IAge Object Invokes method ToString on tree Invokes method ToString on person 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 Test.vb

  48. Defines For Each structure 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 Test.vb

  49. Defines interface IShape Specifies two methods and one property Name 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 Shape.vb

  50. Class Cpoint3 implements interface IShape Declares two Private integers mX and mY Property X 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 Point3.vb

More Related