Chapters 9, 10 – Object-Oriented Programming: Inheritance

Slides:



Advertisements
Similar presentations
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - Object-Oriented Programming: Polymorphism Outline 10.1 Introduction 10.2 Relationships Among.
Advertisements

 2002 Prentice Hall. All rights reserved. 1 Chapter 9 – Object-Oriented Programming: Inheritance Outline 9.1Introduction 9.2Base Classes and Derived Classes.
Object-Oriented Application Development Using VB.NET 1 Chapter 8 Understanding Inheritance and Interfaces.
Chapter 11: Implementing Inheritance and Association Visual Basic.NET Programming: From Problem Analysis to Program Design.
 2002 Prentice Hall. All rights reserved. Some slides modified by LL 1 Chapter 9 – Object-Oriented Programming: Inheritance Outline 9.1Introduction 9.2Base.
VB Classes ISYS 573. Object-Oriented Concepts Abstraction: –To create a model of an object, for the purpose of determining the characteristics (properties)
Object-Oriented Programming in Visual Basic.NET. Overview Defining Classes Creating and Destroying Objects Inheritance Interfaces Working with Classes.
Object-Oriented Programming: Inheritance Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
Object-Oriented Programming: Inheritance
Differences between C# and C++ Dr. Catherine Stringfellow Dr. Stewart Carpenter.
Unit 5 School of Information Systems & Technology1 School of Information Systems and Technology (IST)
Lecture 8 Inheritance Richard Gesick. 2 OBJECTIVES How inheritance promotes software reusability. The concepts of base classes and derived classes. To.
Module 7: Object-Oriented Programming in Visual Basic .NET
Programming Pillars Introduction to Object- Oriented Programming.
 2002 Prentice Hall. All rights reserved. 1 Chapter 9 – Object-Oriented Programming: Inheritance Outline 9.1Introduction 9.2Base Classes and Derived Classes.
 2002 Prentice Hall. All rights reserved. 1 Chapter 10 – Object-Oriented Programming: Polymorphism Outline 10.1 Introduction 10.2 Derived-Class-Object.
 2002 Prentice Hall. All rights reserved. 1 Chapter 9 – Object-Oriented Programming: Inheritance Outline 9.1Introduction 9.2 Base Classes and Derived.
These materials where developed by Martin Schray. Please feel free to use and modify them for non-commercial purposes. If you find them useful or would.
 2003 Prentice Hall, Inc. All rights reserved Case Study: Three-Level Inheritance Hierarchy Three level point/circle/cylinder hierarchy –Point.
 2002 Prentice Hall. All rights reserved. 1 Introduction Polymorphism allows programmers to write: –Programs that handle a wide variety of related classes.
Object-Oriented Application Development Using VB.NET 1 Chapter 8 Understanding Inheritance and Interfaces.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 9 - Object-Oriented Programming: Inheritance Outline 9.1 Introduction 9.2 Superclasses and Subclasses.
VB Classes ISYS 512/812. Object-Oriented Concepts Abstraction: –To create a model of an object, for the purpose of determining the characteristics (properties)
Object Oriented Programming
Chapter 7: Class Inheritance F Superclasses and Subclasses F Keywords: super and this F Overriding methods F The Object Class F Modifiers: protected, final.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
 2002 Prentice Hall. All rights reserved. 1 Chapter 10 – Object-Oriented Programming: Polymorphism Outline 10.1 Introduction 10.2 Derived-Class-Object.
 2002 Prentice Hall. All rights reserved. 1 Passing Methods as Arguments public void BubbleSortArray( int[] array, Comparator Compare ) { for ( int pass.
 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.
Jozef Goetz contribution,  2011 Pearson Education, Inc. All rights reserved.  2002 Prentice Hall. All rights reserved.
Jozef Goetz contribution,  2011, 2014 Pearson Education, Inc. All rights reserved.  2002 Prentice Hall. All rights reserved.
Chapter 2 11/18/2015 © by Pearson Education, Inc. All Rights Reserved. Lect9 GC 2011.
Jozef Goetz contribution, Credits go to  2014, 2011, 2009 Pearson Education, Inc. All rights reserved.  2002 Prentice Hall. All rights reserved.
 2009 Prentice Hall. All rights reserved. 1 Chapter 12 Polymorphism, Interfaces & Operator Overloading [optional] Many slides modified by Prof. L. Lilien.
Object-Oriented Programming: Classes and Objects Chapter 1 1.
 2002 Prentice Hall. All rights reserved. Page 1 Inheritance: Object-Oriented Programming Outline 9.1 Introduction 9.2 Superclasses and Subclasses 9.3.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 10 - Object-Oriented Programming: Polymorphism.
These materials where developed by Martin Schray
Arrays 1.
Chapter 11 Inheritance and Polymorphism
Object-Oriented Programming: Classes and Objects
CIS 200 Test 01 Review.
Inheritance and Polymorphism
One class is an extension of another.
Questions from last lesson
Object-Oriented Programming: Inheritance
IST311 Advanced Issues in OOP: Inheritance and Polymorphism
Chapter 9 – Object-Oriented Programming: Inheritance
 2002 Prentice Hall. All rights reserved.
IST311 Advanced Issues in OOP: Inheritance and Polymorphism
Object-Oriented Programming: Classes and Objects
Object-Oriented Programming: Inheritance
Lecture 23 Polymorphism Richard Gesick.
One class is an extension of another.
Object-Oriented Programming: Inheritance
Chapter 11 – Object-Oriented Programming
Chapter 9 Inheritance and Polymorphism
Lecture 22 Inheritance Richard Gesick.
Week 6 Object-Oriented Programming (2): Polymorphism
IS437: Fall 2004 Instructor: Dr. Boris Jukic
Chapter 9 - Object-Oriented Programming: Inheritance
Polymorphism, Interfaces &
Object-Oriented Programming: Inheritance
Object-Oriented Programming: Classes and Objects
Tonga Institute of Higher Education
Object-Oriented Programming: Inheritance
CIS 199 Final Review.
Classes & Objects A deeper Look Chapter 10 & 11
Chapter 8 Class Inheritance and Interfaces
Object-Oriented Programming: Inheritance
Presentation transcript:

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

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

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

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

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 5 ' implicitly Inherits Object 6 7 ' point coordinate 8 Protected 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 accessible by derived classes but not by other classes

needed to override the method with the same name inherited from object 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 End Class ' CPoint2 needed to override the method with the same name inherited from object

1 ' Fig. 9.10: Circle3.vb 2 ' CCircle3 class that inherits from class CPoint2. 3 4 Public Class CCircle3 5 Inherits CPoint2 ' CCircle3 Inherits from class CPoint2 6 7 Private mRadius As Double ' CCircle3's radius 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 ' implicit call to CPoint2 constructor occurs here 21 mX = xValue 22 mY = yValue 23 Radius = radiusValue 24 End Sub ' New 25 26 ' property Radius 27 Public Property Radius() As Double 28 29 Get 30 Return mRadius 31 End Get 32 33 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

Function ToString overrides function ToString in class CPoint’s 35 If radiusValue > 0 36 mRadius = radiusValue 37 End If 38 39 End Set 40 41 End Property ' Radius 42 43 ' calculate CCircle3 diameter 44 Public Function Diameter() As Double 45 Return mRadius * 2 46 End Function ' Diameter 47 48 ' calculate CCircle3 circumference 49 Public Function Circumference() As Double 50 Return Math.PI * Diameter() 51 End Function ' Circumference 52 53 ' calculate CCircle3 area 54 Public Overridable Function Area() As Double 55 Return Math.PI * mRadius ^ 2 56 End Function ' Area 57 58 ' return String representation of CCircle3 59 Public Overrides Function ToString() As String 60 Return "Center = " & "[" & mX & ", " & mY & "]" & _ 61 "; Radius = " & mRadius 62 End Function ' ToString 63 64 End Class ' CCircle3 CCircle.vb Function ToString overrides function ToString in class CPoint’s

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

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

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)

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 5 Inherits CPoint ' CCircle4 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 Circle4.vb MyBase.New invokes the CPoint constructor explicitly

Circle4.vb 34 If radiusValue > 0 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 CCircle4 circumference 48 Public Function Circumference() As Double 49 Return Math.PI * Diameter() 50 End Function ' Circumference 51 52 ' calculate CCircle4 area 53 Public Overridable Function Area() As Double 54 Return Math.PI * mRadius ^ 2 55 End Function ' Area 56 57 ' return String representation of CCircle4 58 Public Overrides Function ToString() As String 59 60 ' use MyBase reference to return CPoint String representation 61 Return "Center= " & MyBase.ToString() & _ 62 "; Radius = " & mRadius 63 End Function ' ToString 64 65 End Class ' CCircle4 Circle4.vb

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

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

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

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

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

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

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 Point.vb

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 Circle.vb

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 Circle.vb

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 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 polymorphism

Test.vb polymorphism 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 polymorphism

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

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 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 Shape.vb Abstract class Keyword Overridable must accompany every method in abstract class Abstract property (no implementation)

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

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 Point2.vb

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 Circle2.vb

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 Circle2.vb

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

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 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 Cylinder2.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 Test2.vb

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 Test2.vb

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

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

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

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 Person.vb Implementation of Age

Implementation of Name 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 Implementation of Name

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 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 Tree.vb Definition of Age and Name

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

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 Test.vb

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 Test.vb

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

Declaration of a delegate Comparator 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 Comparator DelegateBubbleSort.vb

DelegateBubbleSort.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 DelegateBubbleSort.vb

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 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 FrmBubbleSort.vb

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) FrmBubbleSort.vb

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 FrmBubbleSort.vb

FrmBubbleSort.vb