Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapters 9, 10 – Object-Oriented Programming: Inheritance

Similar presentations


Presentation on theme: "Chapters 9, 10 – Object-Oriented Programming: Inheritance"— Presentation transcript:

1 Chapters 9, 10 – Object-Oriented Programming: Inheritance
Outline Base Classes and Derived Classes, Is-a Relationship, and Inheritance Protected Members Method Overriding Constructors in Derived Classes (*)Finalizers in Derived Classes Substitutability Derived-Class-Object to Base-Class-Object Conversion Polymorphism Abstract Classes (MustInherit) Abstract Methods and Properties (MustOverride) NotInheritable Classes and NotOverridable Methods Interfaces (*) Delegates

2 Base classes and derived classes
inherits the features of is a (special case of / kind of) Fig. 9.1 Some simple inheritance examples.

3 Base Classes and Derived Classes
CommunityMember Employee Student Alumnus Faculty Staff Administrator Teacher Fig. 9.2 Inheritance hierarchy for university CCommunityMembers.

4 Base Classes and Derived Classes
CShape CTwoDimensionalShape CThreeDimensionalShape CCircle CSquare CTriangle CSphere CCube CCylinder Fig. 9.3 Portion of a CShape class hierarchy.

5 accessible by derived classes but not by other classes
1 ' Fig. 9.9: Point2.vb 2 ' CPoint2 class contains an x-y coordinate pair as Protected data. 3 4 Public Class CPoint2 ' implicitly Inherits Object 6 ' point coordinate Protected mX, mY As Integer 9 ' default constructor Public Sub New() 12 ' implicit call to Object constructor occurs here X = 0 Y = 0 End Sub ' New 17 ' constructor Public Sub New(ByVal xValue As Integer, _ ByVal yValue As Integer) 21 ' implicit call to Object constructor occurs here X = xValue Y = yValue End Sub ' New 26 ' property X Public Property X() As Integer 29 Get Return mX End Get 33 accessible by derived classes but not by other classes

6 needed to override the method with the same name inherited from object
Set(ByVal xValue As Integer) mX = xValue ' no need for validation End Set 37 End Property ' X 39 ' property Y Public Property Y() As Integer 42 Get Return mY End Get 46 Set(ByVal yValue As Integer) mY = yValue ' no need for validation End Set 50 End Property ' Y 52 ' return String representation of CPoint2 Public Overrides Function ToString() As String Return "[" & mX & ", " & mY & "]" End Function ' ToString 57 58 End Class ' CPoint2 needed to override the method with the same name inherited from object

7 1 ' Fig. 9.10: Circle3.vb 2 ' CCircle3 class that inherits from class CPoint2. 3 4 Public Class CCircle3 Inherits CPoint2 ' CCircle3 Inherits from class CPoint2 6 Private mRadius As Double ' CCircle3's radius 8 ' default constructor Public Sub New() 11 ' implicit call to CPoint constructor occurs here Radius = 0 End Sub ' New 15 ' constructor Public Sub New(ByVal xValue As Integer, _ ByVal yValue As Integer, ByVal radiusValue As Double) 19 ' implicit call to CPoint2 constructor occurs here mX = xValue mY = yValue Radius = radiusValue End Sub ' New 25 ' property Radius Public Property Radius() As Double 28 Get Return mRadius End Get 32 Set(ByVal radiusValue As Double) 34 Circle3.vb The keyword Inherits indicates inheritance CCircle3 inherits all members of class CPoint2 except constructors Protected members of the base class may be accessed by the derived class (private members cannot), but not by client classes

8 Function ToString overrides function ToString in class CPoint’s
If radiusValue > 0 mRadius = radiusValue End If 38 End Set 40 End Property ' Radius 42 ' calculate CCircle3 diameter Public Function Diameter() As Double Return mRadius * 2 End Function ' Diameter 47 ' calculate CCircle3 circumference Public Function Circumference() As Double Return Math.PI * Diameter() End Function ' Circumference 52 ' calculate CCircle3 area Public Overridable Function Area() As Double Return Math.PI * mRadius ^ 2 End Function ' Area 57 ' return String representation of CCircle3 Public Overrides Function ToString() As String Return "Center = " & "[" & mX & ", " & mY & "]" & _ "; Radius = " & mRadius End Function ' ToString 63 64 End Class ' CCircle3 CCircle.vb Function ToString overrides function ToString in class CPoint’s

9 CCircle.vb 1 ' Fig. 9.11: CircleTest3.vb 2 ' Testing class CCircle3. 3
4 Imports System.Windows.Forms 5 6 Module modCircleTest3 7 Sub Main() Dim circle As CCircle3 Dim output As String 11 circle = New CCircle3(37, 43, 2.5) ' instantiate CCircle3 13 ' get CCircle3's initial x-y coordinates and radius output = "X coordinate is " & circle.X & vbCrLf & _ "Y coordinate is " & circle.Y & vbCrLf & "Radius is " & _ circle.Radius 18 ' set CCircle3's x-y coordinates and radius to new values circle.X = 2 circle.Y = 2 circle.Radius = 4.25 23 ' display CCircle3's String representation output &= vbCrLf & vbCrLf & _ "The new location and radius of circle are " & _ vbCrLf & circle.ToString() & vbCrLf 28 ' display CCircle3's diameter output &= "Diameter is " & _ String.Format("{0:F}", circle.Diameter()) & vbCrLf 32 CCircle.vb

10 CircleTest.vb 33 ' display CCircle3's circumference
output &= "Circumference is " & _ String.Format("{0:F}", circle.Circumference()) & vbCrLf 36 ' display CCircle3's area output &= "Area is " & String.Format("{0:F}", circle.Area()) 39 MessageBox.Show(output, "Demonstrating Class CCircle3") End Sub ' Main 42 43 End Module ' modCircleTest3 CircleTest.vb

11 Constructors and (*)Finalizers in Derived Classes
Constructors in Derived Classes Base-class Base-class constructors are not inherited by derived classes Each base-class constructor initializes the base-class instance variables that the derived-class object inherits * Finalizers in Derived Classes Derived Classes Executing the finalizer method should free all resources acquired by the object before the garbage collector reclaims memory for that object Keyword MyBase is used to invoke the finalizer of the base class (in the end)

12 MyBase.New invokes the CPoint constructor explicitly
1 ' Fig. 9.12: Circle4.vb 2 ' CCircle4 class that inherits from class CPoint. 3 4 Public Class CCircle4 Inherits CPoint ' CCircle4 Inherits from class CPoint 6 Private mRadius As Double 8 ' default constructor Public Sub New() 11 ' implicit call to CPoint constructor occurs here Radius = 0 End Sub ' New 15 ' constructor Public Sub New(ByVal xValue As Integer, _ ByVal yValue As Integer, ByVal radiusValue As Double) 19 ' use MyBase reference to CPoint constructor explicitly MyBase.New(xValue, yValue) Radius = radiusValue End Sub ' New 24 ' property Radius Public Property Radius() As Double 27 Get Return mRadius End Get 31 Set(ByVal radiusValue As Double) 33 Circle4.vb MyBase.New invokes the CPoint constructor explicitly

13 Circle4.vb 34 If radiusValue > 0 35 mRadius = radiusValue 36 End If
37 End Set 39 End Property ' Radius 41 ' calculate CCircle diameter Public Function Diameter() As Double Return mRadius * 2 End Function ' Diameter 46 ' calculate CCircle4 circumference Public Function Circumference() As Double Return Math.PI * Diameter() End Function ' Circumference 51 ' calculate CCircle4 area Public Overridable Function Area() As Double Return Math.PI * mRadius ^ 2 End Function ' Area 56 ' return String representation of CCircle4 Public Overrides Function ToString() As String 59 ' use MyBase reference to return CPoint String representation Return "Center= " & MyBase.ToString() & _ "; Radius = " & mRadius End Function ' ToString 64 65 End Class ' CCircle4 Circle4.vb

14 CircleTest4.vb 1 ' Fig. 9.13: CircleTest4.vb
2 ' Testing class CCircle4. 3 4 Imports System.Windows.Forms 5 6 Module modCircleTest4 7 Sub Main() Dim circle As CCircle4 Dim output As String 11 circle = New CCircle4(37, 43, 2.5) ' instantiate CCircle4 13 ' get CCircle4's initial x-y coordinates and radius output = "X coordinate is " & circle.X & vbCrLf & _ "Y coordinate is " & circle.Y & vbCrLf & "Radius is " & _ circle.Radius 18 ' set CCircle4's x-y coordinates and radius to new values circle.X = 2 circle.Y = 2 circle.Radius = 4.25 23 ' display CCircle4's String representation output &= vbCrLf & vbCrLf & _ "The new location and radius of circle are " & _ vbCrLf & circle.ToString() & vbCrLf 28 ' display CCircle4's diameter output &= "Diameter is " & _ String.Format("{0:F}", circle.Diameter()) & vbCrLf 32 CircleTest4.vb

15 CircleTest4.vb 33 ' display CCircle4's circumference
output &= "Circumference is " & _ String.Format("{0:F}", circle.Circumference()) & vbCrLf 36 ' display CCircle4's area output &= "Area is " & String.Format("{0:F}", circle.Area()) 39 MessageBox.Show(output, "Demonstrating Class CCircle4") End Sub ' Main 42 43 End Module ' modCircleTest4 CircleTest4.vb

16 The opposite is not true
Substitutability An object of a derived class can be treated as an object of its base class An object of a derived class may be passed where an object of its base class is expected The opposite is not true 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

17 Derived-Class-Object to Base-Class-Object Conversion
Also called "upcast" (up in the inheritance tree) Always possible Performed implicitly A consequence of substitutability

18 Polymorphism Dim ref_derived = new DerivedClassName() Dim ref_base as BaseClassName ref_base = ref_derived ref_base.MethodOverridenInDerivedClass() Executes the method implemented in the derived class (the class of the object referenced by ref_derived) The implementation used depends on the object referenced and not on the type of the variable that holds the reference

19 1 ' Fig. 10.1: Point.vb 2 ' CPoint class represents an x-y coordinate pair. 3 4 Public Class CPoint 5 ' point coordinate Private mX, mY As Integer 8 ' default constructor Public Sub New() 11 ' implicit call to Object constructor occurs here X = 0 Y = 0 End Sub ' New 16 ' constructor Public Sub New(ByVal xValue As Integer, _ ByVal yValue As Integer) 20 ' implicit call to Object constructor occurs here X = xValue Y = yValue End Sub ' New 25 ' property X Public Property X() As Integer 28 Get Return mX End Get 32 Set(ByVal xValue As Integer) mX = xValue ' no need for validation End Set Point.vb

20 Point.vb 36 37 End Property ' X 38 39 ' property Y
Public Property Y() As Integer 41 Get Return mY End Get 45 Set(ByVal yValue As Integer) mY = yValue ' no need for validation End Set 49 End Property ' Y 51 ' return String representation of CPoint Public Overrides Function ToString() As String Return "[" & mX & ", " & mY & "]" End Function ' ToString 56 57 End Class ' CPoint Point.vb

21 Circle.vb 1 ' Fig. 10.2: Circle.vb
2 ' CCircle class that inherits from class CPoint. 3 4 Public Class CCircle Inherits CPoint ' CCircle Inherits from class CPoint 6 Private mRadius As Double 8 ' default constructor Public Sub New() 11 ' implicit call to CPoint constructor occurs here Radius = 0 End Sub ' New 15 ' constructor Public Sub New(ByVal xValue As Integer, _ ByVal yValue As Integer, ByVal radiusValue As Double) 19 ' use MyBase reference to CPoint constructor explicitly MyBase.New(xValue, yValue) Radius = radiusValue End Sub ' New 24 ' property Radius Public Property Radius() As Double 27 Get Return mRadius End Get 31 Set(ByVal radiusValue As Double) 33 Circle.vb

22 Circle.vb 34 If radiusValue >= 0 ' mRadius must be nonnegative
mRadius = radiusValue End If 37 End Set 39 End Property ' Radius 41 ' calculate CCircle diameter Public Function Diameter() As Double Return mRadius * 2 End Function ' Diameter 46 ' calculate CCircle circumference Public Function Circumference() As Double Return Math.PI * Diameter() End Function ' Circumference 51 ' calculate CCircle area Public Overridable Function Area() As Double Return Math.PI * mRadius ^ 2 End Function ' Area 56 ' return String representation of CCircle Public Overrides Function ToString() As String 59 ' use MyBase reference to return CCircle String representation Return "Center= " & MyBase.ToString() & _ "; Radius = " & mRadius End Function ' ToString 64 65 End Class ' CCircle Circle.vb

23 Test.vb polymorphism 1 ' Fig. 10.3: Test.vb
2 ' Demonstrating inheritance and polymorphism. 3 4 Imports System.Windows.Forms 5 6 Class CTest 7 ' demonstrate "is a" relationship Shared Sub Main() Dim output As String Dim point1, point2 As CPoint Dim circle1, circle2 As CCircle 13 point1 = New CPoint(30, 50) circle1 = New CCircle(120, 89, 2.7) 16 output = "CPoint point1: " & point1.ToString() & _ vbCrLf & "CCircle circle1: " & circle1.ToString() 19 ' use is-a relationship to assign CCircle to CPoint reference point2 = circle1 22 output &= vbCrLf & vbCrLf & _ "CCircle circle1 (via point2): " & point2.ToString() 25 ' downcast (cast base-class reference to derived-class ' data type) point2 to circle2 circle2 = CType(point2, CCircle) ' allowed only via cast 29 output &= vbCrLf & vbCrLf & _ "CCircle circle1 (via circle2): " & circle2.ToString() 32 output &= vbCrLf & "Area of circle1 (via circle2): " & _ String.Format("{0:F}", circle2.Area()) 35 Test.vb polymorphism

24 Test.vb polymorphism 36 ' assign CPoint object to CCircle reference
If (TypeOf point1 Is CCircle) Then circle2 = CType(point1, CCircle) output &= vbCrLf & vbCrLf & "cast successful" Else output &= vbCrLf & vbCrLf & _ "point1 does not refer to a CCircle" End If 44 MessageBox.Show(output, _ "Demonstrating the 'is a' relationship") End Sub ' Main 48 49 End Class ' CTest Test.vb polymorphism

25 Abstract Classes, Methods and Properties
Cannot be instantiated ( New AbstractClassName ) A class is made abstract by using keyword MustInherit Normally contains one or more abstract methods or properties Keyword MustOverride declares a method or property as abstract MustOverride methods and properties do not provide implementations

26 Abstract property (no implementation)
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 ' return shape area Public Overridable Function Area() As Double Return 0 End Function ' Area 12 ' return shape volume Public Overridable Function Volume() As Double Return 0 End Function ' Volume 17 ' overridable method that should return shape name Public MustOverride ReadOnly Property Name() As String 20 21 End Class ' CShape Shape.vb Abstract class Keyword Overridable must accompany every method in abstract class Abstract property (no implementation)

27 1 ' Fig. 10.5: Point2.vb 2 ' CPoint2 class represents an x-y coordinate pair. 3 4 Public Class CPoint2 Inherits CShape ' CPoint2 inherits from MustInherit class CShape 6 ' point coordinate Private mX, mY As Integer 9 ' default constructor Public Sub New() 12 ' implicit call to Object constructor occurs here X = 0 Y = 0 End Sub ' New 17 ' constructor Public Sub New(ByVal xValue As Integer, _ ByVal yValue As Integer) 21 ' implicit call to Object constructor occurs here X = xValue Y = yValue End Sub ' New 26 ' property X Public Property X() As Integer 29 Get Return mX End Get 33 Point2.vb

28 Point2.vb 34 Set(ByVal xValue As Integer)
mX = xValue ' no need for validation End Set 37 End Property ' X 39 ' property Y Public Property Y() As Integer 42 Get Return mY End Get 46 Set(ByVal yValue As Integer) mY = yValue ' no need for validation End Set 50 End Property ' Y 52 ' return String representation of CPoint2 Public Overrides Function ToString() As String Return "[" & mX & ", " & mY & "]" End Function ' ToString 57 ' implement MustOverride property of class CShape Public Overrides ReadOnly Property Name() As String 60 Get Return "CPoint2" End Get 64 End Property ' Name 66 67 End Class ' CPoint2 Point2.vb

29 Circle2.vb 1 ' Fig. 10.6: Circle2.vb
2 ' CCircle2 class inherits from CPoint2 and overrides key members. 3 4 Public Class CCircle2 Inherits CPoint2 ' CCircle2 Inherits from class CPoint2 6 Private mRadius As Double 8 ' default constructor Public Sub New() 11 ' implicit call to CPoint2 constructor occurs here Radius = 0 End Sub ' New 15 ' constructor Public Sub New(ByVal xValue As Integer, _ ByVal yValue As Integer, ByVal radiusValue As Double) 19 ' use MyBase reference to CPoint2 constructor explicitly MyBase.New(xValue, yValue) Radius = radiusValue End Sub ' New 24 ' property Radius Public Property Radius() As Double 27 Get Return mRadius End Get 31 Set(ByVal radiusValue As Double) 33 If radiusValue >= 0 ' mRadius must be nonnegative mRadius = radiusValue Circle2.vb

30 Circle2.vb 36 End If 37 38 End Set 39 40 End Property ' Radius 41
' calculate CCircle2 diameter Public Function Diameter() As Double Return mRadius * 2 End Function ' Diameter 46 ' calculate CCircle2 circumference Public Function Circumference() As Double Return Math.PI * Diameter() End Function ' Circumference 51 ' calculate CCircle2 area Public Overrides Function Area() As Double Return Math.PI * mRadius ^ 2 End Function ' Area 56 ' return String representation of CCircle2 Public Overrides Function ToString() As String 59 ' use MyBase to return CCircle2 String representation Return "Center = " & MyBase.ToString() & _ "; Radius = " & mRadius End Function ' ToString 64 ' override property Name from class CPoint2 Public Overrides ReadOnly Property Name() As String 67 Get Return "CCircle2" End Get Circle2.vb

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

32 Cylinder2.vb 1 ' Fig. 10.7: Cylinder2.vb
2 ' CCylinder2 inherits from CCircle2 and overrides key members. 3 4 Public Class CCylinder2 Inherits CCircle2 ' CCylinder2 inherits from class CCircle2 6 Protected mHeight As Double 8 ' default constructor Public Sub New() 11 ' implicit call to CCircle2 constructor occurs here Height = 0 End Sub ' New 15 ' four-argument constructor Public Sub New(ByVal xValue As Integer, _ ByVal yValue As Integer, ByVal radiusValue As Double, _ ByVal heightValue As Double) 20 ' explicit call to CCircle2 constructor MyBase.New(xValue, yValue, radiusValue) Height = heightValue ' set CCylinder2 height End Sub ' New 25 ' property Height Public Property Height() As Double 28 Get Return mHeight End Get 32 ' set CCylinder2 height if argument value is positive Set(ByVal heightValue As Double) 35 Cylinder2.vb

33 36 If heightValue >= 0 Then ' mHeight must be nonnegative
mHeight = heightValue End If 39 End Set 41 End Property ' Height 43 ' override method Area to calculate CCylinder2 surface area Public Overrides Function Area() As Double Return 2 * MyBase.Area + MyBase.Circumference * mHeight End Function ' Area 48 ' calculate CCylinder2 volume Public Overrides Function Volume() As Double Return MyBase.Area * mHeight End Function ' Volume 53 ' convert CCylinder2 to String Public Overrides Function ToString() As String Return MyBase.ToString() & "; Height = " & mHeight End Function ' ToString 58 ' override property Name from class CCircle2 Public Overrides ReadOnly Property Name() As String 61 Get Return "CCylinder2" End Get 65 End Property ' Name 67 68 End Class ' CCylinder2 Cylinder2.vb

34 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 Shared Sub Main() 9 ' instantiate CPoint2, CCircle2 and CCylinder2 objects Dim point As New CPoint2(7, 11) Dim circle As New CCircle2(22, 8, 3.5) Dim cylinder As New CCylinder2(10, 10, 3.3, 10) 14 ' instantiate array of base-class references Dim arrayOfShapes As CShape() = New CShape(2){} 17 ' arrayOfShapes(0) refers to CPoint2 object arrayOfShapes(0) = point 20 ' arrayOfShapes(1) refers to CCircle2 object arrayOfShapes(1) = circle 23 ' arrayOfShapes(2) refers to CCylinder2 object arrayOfShapes(2) = cylinder 26 Dim output As String = point.Name & ": " & _ point.ToString() & vbCrLf & circle.Name & ": " & _ circle.ToString() & vbCrLf & cylinder.Name & _ ": " & cylinder.ToString() 31 Dim shape As CShape 33 Test2.vb

35 Test2.vb 34 ' display name, area and volume for each object in
' arrayOfShapes polymorphically For Each shape In arrayOfShapes output &= vbCrLf & vbCrLf & shape.Name & ": " & _ shape.ToString() & vbCrLf & "Area = " & _ String.Format("{0:F}", shape.Area) & vbCrLf & _ "Volume = " & String.Format("{0:F}", shape.Volume) Next 42 MessageBox.Show(output, "Demonstrating Polymorphism") End Sub ' Main 45 46 End Class ' CTest2 Test2.vb

36 NottInheritable Classes and NotOverridable Methods and Properties
Cannot be inherited by other classes Keyword NottInheritable NotOverridable Methods and Properties Cannot be overridden in derived classes Keyword NotOverridable

37 Interfaces An interface may be seen as a fully abstract class
Interface definition begins with keyword Interface Contains a list of public and abstract methods and properties Interfaces are implemented by classes, that is, the properties and methods specified in the interface must be implemented by classes that implement the interface A class may implement multiple interfaces (but can only inherit from a single base class) Many examples in the .Net class libraries

38 1 ' Fig : IAge.vb 2 ' Interface IAge declares property for setting and getting age. 3 4 Public Interface IAge 5 ' classes that implement IAge must define these properties ReadOnly Property Age() As Integer ReadOnly Property Name() As String 9 10 End Interface ' IAge IAge.vb

39 1 ' Fig : Person.vb 2 ' Class CPerson has a birthday. 3 4 Public Class CPerson Implements IAge 6 Private mYearBorn As Integer Private mFirstName As String Private mLastName As String 10 ' constructor receives first name, last name and birth date Public Sub New(ByVal firstNameValue As String, _ ByVal lastNameValue As String, _ ByVal yearBornValue As Integer) 15 ' implicit call to Object constructor mFirstName = firstNameValue mLastName = lastNameValue 19 ' validate year If (yearBornValue > 0 AndAlso _ yearBornValue <= Date.Now.Year) 23 mYearBorn = yearBornValue Else mYearBorn = Date.Now.Year End If 28 End Sub ' New 30 ' property Age implementation of interface IAge ReadOnly Property Age() As Integer _ Implements IAge.Age 34 Keyword Implements indicates that class CPerson implements interface IAge Person.vb Implementation of Age

40 Implementation of Name
Get Return Date.Now.Year - mYearBorn End Get 38 End Property ' Age 40 ' property Name implementation of interface IAge ReadOnly Property Name() As String _ Implements IAge.Name 44 Get Return mFirstName & " " & mLastName End Get 48 End Property ' Name 50 51 End Class ' CPerson Person.vb Implementation of Name

41 Definition of Age and Name
1 ' Fig : Tree.vb 2 ' Class CTree contains number of rings corresponding to age. 3 4 Public Class CTree Implements IAge 6 Private mRings As Integer 8 ' constructor receives planting date Public Sub New(ByVal yearPlanted As Integer) 11 ' implicit call to Object constructor mRings = Date.Now.Year - yearPlanted End Sub ' New 15 ' increment mRings Public Sub AddRing() mRings += 1 End Sub ' AddRing 20 ' property Age ReadOnly Property Age() As Integer _ Implements IAge.Age 24 Get Return mRings End Get 28 End Property ' Age 30 ' property Name implementation of interface IAge ReadOnly Property Name() As String _ Implements IAge.Name 34 Tree.vb Definition of Age and Name

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

43 Test.vb 1 ' Fig. 10.18: Test.vb 2 ' Demonstrate polymorphism. 3
4 Imports System.Windows.Forms 5 6 Class CTest 7 Shared Sub Main() 9 ' instantiate CTree and CPerson objects Dim tree As New CTree(1976) Dim person As New CPerson("Bob", "Jones", 1983) 13 ' instantiate array of interface references Dim iAgeArray As IAge() = New IAge(1){} 16 ' iAgeArray(0) references CTree object iAgeArray(0) = tree 19 ' iAgeArray(1) references CPerson object iAgeArray(1) = person 22 ' display tree information Dim output As String = tree.ToString() & ": " & _ tree.Name & vbCrLf & "Age is " & tree.Age & vbCrLf & _ vbCrLf 27 ' display person information output &= person.ToString() & ": " & _ person.Name & vbCrLf & "Age is " & person.Age & _ vbCrLf 32 Dim ageReference As IAge 34 Test.vb

44 Test.vb 35 ' display name and age for each IAge object in iAgeArray
For Each ageReference In iAgeArray output &= vbCrLf & ageReference.Name & ": " & _ "Age is " & ageReference.Age Next 40 MessageBox.Show(output, "Demonstrating Polymorphism") End Sub ' Main 43 44 End Class ' CTest Test.vb

45 Are classes that encapsulate a set of references to methods
* Delegates Are 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

46 Declaration of a delegate Comparator
1 ' Fig : DelegateBubbleSort.vb 2 ' Uses delegates to sort random numbers (ascending or descending). 3 4 Public Class CDelegateBubbleSort 5 ' delegate definition Public Delegate Function Comparator( _ ByVal element1 As Integer, _ ByVal element2 As Integer) As Boolean 10 ' sort array depending on comparator Public Sub SortArray(ByVal array As Integer(), _ ByVal Compare As Comparator) 14 Dim i, pass As Integer 16 For pass = 0 To array.GetUpperBound(0) 18 ' comparison inner loop For i = 0 To array.GetUpperBound(0) - 1 21 If Compare(array(i), array(i + 1)) Then Swap(array(i), array(i + 1)) End If 25 Next ' inner loop 27 Next ' outer loop 29 End Sub ' SortArray 31 ' swap two elements Private Sub Swap(ByRef firstElement As Integer, _ ByRef secondElement As Integer) 35 Declaration of a delegate Comparator DelegateBubbleSort.vb

47 DelegateBubbleSort.vb 36 Dim hold As Integer 37 38 hold = firstElement
firstElement = secondElement secondElement = hold End Sub ' Swap 42 43 End Class ' CDelegateBubbleSort DelegateBubbleSort.vb

48 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 Inherits Form 8 ' TextBox that contains original list Friend WithEvents txtOriginal As TextBox Friend WithEvents lblOriginal As Label 12 ' TextBox that contains sorted list Friend WithEvents txtSorted As TextBox Friend WithEvents lblSorted As Label 16 ' Buttons for creating and sorting lists Friend WithEvents cmdCreate As Button Friend WithEvents cmdSortAscending As Button Friend WithEvents cmdSortDescending As Button 21 ' Windows Form Designer generate code 23 ' reference to object containing delegate Dim mBubbleSort As New CDelegateBubbleSort() 26 ' original array with unsorted elements Dim mElementArray As Integer() = New Integer(9){} 29 ' delegate implementation sorts in asending order Private Function SortAscending(ByVal element1 As Integer, _ ByVal element2 As Integer) As Boolean 33 Return element1 > element2 End Function ' SortAscending FrmBubbleSort.vb

49 36 ' delegate implementation sorts in descending order Private Function SortDescending(ByVal element1 As Integer, _ ByVal element2 As Integer) As Boolean 40 Return element1 < element2 End Function ' SortDescending 43 ' creates random generated numbers Private Sub cmdCreate_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdCreate.Click 47 txtSorted.Clear() 49 Dim output As String Dim randomNumber As Random = New Random() Dim i As Integer 53 ' create String with 10 random numbers For i = 0 To mElementArray.GetUpperBound(0) mElementArray(i) = randomNumber.Next(100) output &= mElementArray(i) & vbCrLf Next 59 txtOriginal.Text = output ' display numbers 61 ' enable sort buttons cmdSortAscending.Enabled = True cmdSortDescending.Enabled = True End Sub ' cmdCreate_Click 66 FrmBubbleSort.vb

50 FrmBubbleSort.vb 67 ' display array contents in specified TextBox
Private Sub DisplayResults() 69 Dim output As String Dim i As Integer 72 ' create string with sorted numbers For i = 0 To mElementArray.GetUpperBound(0) output &= mElementArray(i) & vbCrLf Next 77 txtSorted.Text = output ' display numbers End Sub ' DisplayResults 80 ' sorts randomly generated numbers in ascending manner Private Sub cmdSortAscending_Click(ByVal sender As _ System.Object, ByVal e As System.EventArgs) _ Handles cmdSortAscending.Click 85 ' sort array mBubbleSort.SortArray(mElementArray, AddressOf SortAscending) 88 DisplayResults() ' display results 90 cmdSortAscending.Enabled = False cmdSortDescending.Enabled = True End Sub ' cmdSortAscending_Click 94 ' sorts randomly generated numbers in descending manner Private Sub cmdSortDescending_Click(ByVal sender As _ System.Object, ByVal e As System.EventArgs) _ Handles cmdSortDescending.Click 99 ' create sort object and sort array mBubbleSort.SortArray(mElementArray, AddressOf SortDescending) FrmBubbleSort.vb

51 FrmBubbleSort.vb 102 103 DisplayResults() ' display results 104
cmdSortDescending.Enabled = False cmdSortAscending.Enabled = True End Sub ' cmdSortDescending_Click 108 109 End Class ' CFrmBubbleSort FrmBubbleSort.vb

52 FrmBubbleSort.vb


Download ppt "Chapters 9, 10 – Object-Oriented Programming: Inheritance"

Similar presentations


Ads by Google