52
The Visual Basic .NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic .NET is considered an object. When everything is an object, it allows you to create new objects from the existing objects. If the objects that come with Visual Basic .NET do not meet your needs, you do not have to start from scratch. Instead, you can start with an object that contains the majority of the functionality you require and create a new object that inherits the original object’s functionality but also contains the additional information.

The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

  • View
    221

  • Download
    0

Embed Size (px)

Citation preview

Page 1: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

1

Chapter 10 – Advanced Object-Oriented Programming

Everything in Visual Basic .NET is considered an object.

When everything is an object, it allows you to create new objects from the existing objects.

If the objects that come with Visual Basic .NET do not meet your needs, you do not have to start from scratch.

Instead, you can start with an object that contains the majority of the functionality you require and create a new object that inherits the original object’s functionality but also contains the additional information.

Page 2: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

2

10.1 Visual InheritanceAs you develop applications you will find that your objects are required in more than one application.

Often the object will require modifications in order for it to work properly in the new application.

While you can just copy the code associated with the object to the new application and then modify it there, this would cause a number of potential problems.

A minor problem is that you are wasting space on your hard drive.

If you have the definition in numerous places, you will have to make the correction in numerous places.

Chapter 10 – Advanced Object-Oriented Programming

Page 3: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

3

Inheritance is the ability to create one object from another.

With inheritance you will create a simple class to define an object that will be common to many other objects and then create other classes based on the original class, but with more features.

The original class is known as the base class,

The classes created from the base class are known as derived classes.

Visual Basic .NET not only allows you to code classes with inheritance, but you can also inherit visually.

Visual inheritance allows the developer to inherit forms and controls to create new forms and controls.

Chapter 10 – Advanced Object-Oriented Programming

Page 4: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

4

With visual inheritance you can create the form that all forms are to model and then tell Visual Basic .NET that you wish to create a form based on the original form.

With visual inheritance, if you make a change to the original form, all that is required is that you rebuild your applications and the applications will automatically update themselves to reflect any changes to the base form.

To create a form that inherits its properties from a previous existing form, like the one just discussed, you should follow these steps:

Step 1: Create a form, frmBase, with a logo in the upper-left corner and a copyright in the lower-left corner:

Chapter 10 – Advanced Object-Oriented Programming

Page 5: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

5

Step 2: Select Add Inherited Form from the Project menu.

Step 3: Select Open from the dialog box that appears:

Chapter 10 – Advanced Object-Oriented Programming

Page 6: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

6

Step 4: Select InheritedForm from the Templates. It should be the default.

Change the Name of the form from Form1.vb to the name you wish your new form to be called.

You will use frmDerived.vb for this example.

Click on the Open button.

The dialog box shown here will appear.

Chapter 10 – Advanced Object-Oriented Programming

Page 7: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

7

Step 5: Select frmBase as the form you wish to base your new form on.

Click on the OK button and your new form should appear and look similar to the base form that you created it from:

Chapter 10 – Advanced Object-Oriented Programming

Notice the small arrows on the label and picture box that were inherited from the base form.

This is your way of differentiating the objects you have added to the derived form versus the objects you have inherited from the base form.

Page 8: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

8

Visual inheritance applies to any controls or code that you include in a base class or object.

Imagine if you created a single form containing the common demographic data for people.

You could create a form with controls to gather the person’s first name, middle initial, last name, street address, city, state, ZIP code, email address, and so on.

Then additional forms could inherit from this form the basic information and add the information pertinent to the specific group they belonged to.

The code associated with the basic information could also be contained in the base form and added to the derived forms.

This allows you to modify the basic demographic information in one place and again have it propagate through all the company’s applications with a minimum of effort.

Visual inheritance is an excellent way to enforce uniformity across a company.

Chapter 10 – Advanced Object-Oriented Programming

Page 9: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

9

10.2 Inheritance in Code

Protected KeywordA property defined with the Private keyword allows only methods and events of the class the property is defined in to have access to it.

In contrast, a property defined with a scope of Public allowed any routine to have access to it.

When a base class is going to be inherited, you’ll want the properties of the base class to be accessible by methods of the derived class.

In these cases, you will need to define a property with a scope of Protected.

If you attempt to access an attribute in a base class from a derived class that is defined with a Private scope, it will not be accessible from methods in the derived class.

The syntax for declaring a property with a Protected scope is as follows:

Chapter 10 – Advanced Object-Oriented Programming

Protected PropertyName As DataType

Page 10: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

10

Overriding Methods Defined in a Base ClassWhen a method is defined in a base class, you can decide whether or not that method can be changed in the derived class.

Allow the overriding of a method in the derived classes.

You must add the Overridable keyword to the base class method definition:

Chapter 10 – Advanced Object-Oriented Programming

Public Overridable Function MethodName(ParameterName As Datatype) As Datatype

'Body of MethodEnd Function

Public Overridable Sub MethodName(ParameterName As Datatype) 'Body of MethodEnd Sub

Page 11: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

11

Defining a Derived ClassTo define a new class that is derived from a base class, you must declare the name and scope of the class as before.

You must follow the name with the keyword Inherits as well as the name of the base class.

Observe the following syntax:

Chapter 10 – Advanced Object-Oriented Programming

Public Class DerivedClassName Inherits BaseClassName

Page 12: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

12

Clock/Alarm Clock ExampleStart with a class that you have already defined, the Clock class from one of the previous examples.

Implement an AlarmClock class.

The AlarmClock class will function in a similar manner to the Clock class, except that it will add the functionality of an alarm to the class.

This will require storing the time the alarm could be set for and whether the alarm is set or not.

It will also require allowing the user to set the alarm.

Your clock will keep military time and should track hours, minutes, and seconds.

Therefore, you will need three attributes, each of which will be stored as Integers.

Each of these attributes will be Protected in scope because you wish to allow them to be accessible by derived classes.

Chapter 10 – Advanced Object-Oriented Programming

Page 13: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

13

Class DeclarationWhen you declare a class that will act as a base class for derived classes, initially there appears to be no difference.

Observe how your Clock class is defined with the same syntax:

Chapter 10 – Advanced Object-Oriented Programming

Public Class Clock

Page 14: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

14

Property DeclarationNext you must declare any properties required for your base class.

If you wish the properties to be visible in the derived classes, you must use the Protected keyword to define the scope.

Chapter 10 – Advanced Object-Oriented Programming

Protected mintHour As IntegerProtected mintMinute As IntegerProtected mintSecond As Integer

Page 15: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

15

Property StatementsCreate property statements to access the new properties.

Chapter 10 – Advanced Object-Oriented Programming

Public Property Hour() As Integer Get

Return mintHour End Get Set(ByVal Value As Integer)

mintHour = Value End SetEnd PropertyPublic Property Minute() As Integer Get

Return mintMinute End Get Set(ByVal Value As Integer)

mintMinute = Value End SetEnd PropertyPublic Property Second() As Integer Get

Return mintSecond End Get Set(ByVal Value As Integer)

mintSecond = Value End SetEnd Property

Page 16: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

16

ConstructorsCode two constructors.

The first will be the default constructor that will accept no parameters. It will initialize the clock to 12:00.

Chapter 10 – Advanced Object-Oriented Programming

Public Sub New() minthour = 12 mintminute = 0 mintsecond = 0End Sub

The second constructor will accept parameters for the hour, minute, and second to initialize your clock.

All parameters must be present in order for this constructor to be called.

Public Sub New(ByVal intH As Integer, ByVal intM As Integer, _ByVal intS As Integer)

minthour = intH mintminute = intM mintsecond = intSEnd Sub

Page 17: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

17

MethodsThe next method to implement is to display the time.

Because this method will be overridden in the derived class, you add the keyword Overridable to the method definition.

Chapter 10 – Advanced Object-Oriented Programming

Public Overridable Function Time() As String Return mintHour.ToString & ":" & mintMinute.ToString & _

":" & mintSecond.ToStringEnd Function

Page 18: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

18

Methods ContinuedThe Increment method must also be declared as Overridable, because you will need to change its implementation in the derived class.

Chapter 10 – Advanced Object-Oriented Programming

Public Overridable Sub Increment() mintSecond += 1 If (mintSecond = 60) Then

mintSecond = 0mintMinute += 1If (mintMinute = 60) Then mintMinute = 0 mintHour = mintHour + 1 If mintHour = 24 Then

mintHour = 0 End IfEnd If

End IfEnd Sub

Page 19: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

19

Methods ContinuedThe goal in creating the AlarmClock class is to rewrite the least amount of code possible from the Clock class.

The properties for the Clock class are all required in the AlarmClock class.

You need additional properties to store the alarm time and whether or not the alarm is set.

You need to create a SetAlarm method as well as a ShutAlarm method to set and shut off the alarm.

When the Time method is called, display an asterisk next to the time when the alarm is set.

You can call the Time method in the base class and add the code you require in the derived class.

Chapter 10 – Advanced Object-Oriented Programming

Page 20: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

20

Methods ContinuedDeclare the derived method using the keyword Overrides.

The syntax for declaring a method that overrides a base class’s method is as follows:

Chapter 10 – Advanced Object-Oriented Programming

Public Overrides Function MethodName(Parameter List) As DataTypePublic Overrides Sub MethodName(Parameter List)

To use the functionality of a base class’s method, use the following syntax of code to explicitly call the method wherever you wish it to be called in the new method.

MyBase.OriginalMethod

Page 21: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

21

Methods ContinuedDeclare AlarmClock as a class that inherits the properties and methods of the Clock class.

Chapter 10 – Advanced Object-Oriented Programming

Public Class AlarmClock Inherits Clock

Page 22: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

22

Methods ContinuedDeclare any additional properties required for your derived class:

Chapter 10 – Advanced Object-Oriented Programming

Private mintAlarmHour As IntegerPrivate mintAlarmMinute As IntegerPrivate mintAlarmSecond As IntegerPrivate mintAlarmSet As Boolean

Page 23: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

23

Methods ContinuedCreate any Get/Set statements required for the new properties:

Chapter 10 – Advanced Object-Oriented Programming

Public Property AlarmHour() As Integer Get

Return mintAlarmHour End Get Set(ByVal Value As Integer)

mintAlarmHour = Value End SetEnd PropertyPublic Property AlarmMinute() As Integer Get

Return mintAlarmMinute End Get Set(ByVal Value As Integer)

mintAlarmMinute = Value End SetEnd PropertyPublic Property AlarmSecond() As Integer Get

Return mintAlarmSecond End Get Set(ByVal Value As Integer)

mintAlarmSecond = Value End SetEnd Property

Page 24: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

24

Methods ContinuedCreate a new constructor.

You need to initialize any of the new properties defined for the derived class or if the derived class behaves differently than the base class. Initialize the alarm in the clock to be off.

You should call the base class’s constructor and pass it all of the parameters it requires.

You can simply set mintAlarmSet to False and your constructor would look as follows:

Chapter 10 – Advanced Object-Oriented Programming

Public Sub New(ByVal intH As Integer, ByVal intM As Integer, _ ByVal intS As Integer)

MyBase.New(intH, intM, intS) mintAlarmSet = FalseEnd Sub

Page 25: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

25

Methods ContinuedYour Increment method shared functionality between the base case and the derived class.

You wish the Increment method to add a second to the clock, as it did in the base class.

Then you wish it to compare the current clock time to the alarm’s time.

If they are the same, you will pop up a message box indicating the alarm has rung.

Explicitly call the base class’s Increment method and then perform the check comparing the base class’s properties to the derived class’s properties.

Chapter 10 – Advanced Object-Oriented Programming

Public Overrides Sub Increment() MyBase.Increment() If (mintAlarmHour = mintHour) _

And (mintAlarmMinute = mintAlarmMinute) _And (mintAlarmSecond = mintAlarmSecond) Then

MsgBox("ALARM") End IfEnd Sub

Page 26: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

26

Methods ContinuedThe SetAlarm method does not exist in the base class, so it does not contain the Overrides keyword.

The contents of the method set the attributes for the alarm time to the values passed as parameters as well as setting the alarm to on by setting the mintAlarmSet attribute to True.

Chapter 10 – Advanced Object-Oriented Programming

Public Sub SetAlarm(ByVal intH As Integer, ByVal intM As Integer, _ ByVal intS As Integer)

mintAlarmHour = intH mintAlarmMinute = intM mintAlarmSecond = intS mintAlarmSet = TrueEnd Sub

Page 27: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

27

Methods ContinuedThe ShutAlarm method does not exist in the base class, so it does not contain the Overrides keyword.

The contents of the method set the attribute mintAlarmSet to False.

Chapter 10 – Advanced Object-Oriented Programming

Public Sub ShutAlarm() mintAlarmSet = FalseEnd Sub

Page 28: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

28

Methods ContinuedThe Time method shared functionality between the base case and the derived class.

Your Time method should display the time as it did in the base class.

If the alarm is set, it should also display an asterisk next to the time.

Explicitly call the base class’s Time method and add an asterisk if the alarm is set.

Chapter 10 – Advanced Object-Oriented Programming

Public Overrides Function Time() As String If (mintAlarmSet = True) Then

Return MyBase.Time() & " *" Else

Return MyBase.Time() End IfEnd Function

Page 29: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

29

10.3 PolymorphismPolymorphism allows you to develop your classes to contain methods with the same name but different parameter lists.

Sometimes you will have a method that will behave differently if a different type of parameter is passed.

We have already seen polymorphism at work when different objects use the same name to produce results.

We have already seen operators accept different objects and perform the proper operation.

You have created constructors that initialize a class with different numbers of parameters, but Visual Basic .NET’s polymorphic capabilities do not end there.

Chapter 10 – Advanced Object-Oriented Programming

Page 30: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

30

Overloading MethodsAs long as the parameter list varies, you can create more than one method with the same name.

By modifying the declaration of a method, you can create as many methods with the same name in a single class as long as the parameter list varies in each and every method with the same name.

The following syntax is used for a function or subroutine method that will exist in more than one form.

The only difference between this declaration and the original declaration is the addition of the Overloads keyword at the beginning of the statement.

Chapter 10 – Advanced Object-Oriented Programming

Public Overloads Sub MethodName(ParameterList) Body of MethodEnd Sub

Public Overloads Function MethodName(ParameterList) As Datatype Body of MethodEnd Function

Page 31: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

31

Drill 10.1Do the following method definitions conflict or are they valid definitions for a class?

Chapter 10 – Advanced Object-Oriented Programming

Public Sub DrillMethod(ByVal Param1 As Integer) 'Body of MethodEnd Sub

Public Sub DrillMethod(ByVal Param1 As String) 'Body of MethodEnd Sub

Answer: the following definitions conflict.

Page 32: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

32

Drill 10.2Do the following method definitions conflict or are they valid definitions for a class?

Chapter 10 – Advanced Object-Oriented Programming

Public Overloads Sub DrillMethod(ByVal Param1 As Integer) 'Body of MethodEnd Sub

Public Overloads Sub DrillMethod(ByVal FirstParam As String) 'Body of MethodEnd Sub

Answer: the following definitions do not conflict.

Page 33: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

33

Drill 10.3Do the following method definitions conflict or are they valid definitions for a class?

Chapter 10 – Advanced Object-Oriented Programming

Public Overloads Sub DrillMethod(ByVal Param1 As Integer) 'Body of MethodEnd Sub

Public Overloads Sub DrillMethod(ByVal Param1 As Integer, _ByVal Param2 As String)

'Body of MethodEnd Sub

Answer: the following definitions do not conflict.

Page 34: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

34

Example: Adding Polymorphism to Your Clock ClassAdd a method to the Clock class called SetTime.

This method will take on many forms.

This can be implemented by creating three versions of the SetTime method.

The first implementation will accept only a single Integer to set the current hour.

The second implementation will accept two Integers: one for the hour and one for the minute.

The third implementation will accept three Integers: one for the hour, one for the minute, and one for the second.

Chapter 10 – Advanced Object-Oriented Programming

Public Overloads Sub SetTime(ByVal intHour As Integer) mintHour = intHour 'Set the Hour to the parameter mintMinute = 0 'Reset minutes to 0 mintSecond = 0 'Reset seconds to 0End Sub

Page 35: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

35

Example: Adding Polymorphism to Your Clock Class (Continued)

Chapter 10 – Advanced Object-Oriented Programming

Public Overloads Sub SetTime(ByVal intHour As Integer, _ ByVal intMinute As Integer)

mintHour = intHour 'Set the Hour to the parameter mintMinute = intMinute 'Set the Minutes to the parameter mintSecond = 0 'Reset seconds to 0End Sub

Public Overloads Sub SetTime(ByVal intHour As Integer, _ByVal intMinute As Integer, ByVal intSecond As Integer)

mintHour = intHour 'Set the Hour to the parameter mintMinute = intMinute 'Set the Minutes to the parameter mintSecond = intSecond 'Set the Seconds to the parameterEnd Sub

Page 36: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

36

10.4 DestructorsMany of your classes should include a method called the destructor.

A destructor is the last method called when the object’s resources are being returned to the operating system.

This method is usually used to indicate resources that are not automatically returned.

Visual Basic .NET uses a system called garbage collection.

When garbage collection is employed, one does not know exactly when resources will be returned to the operating system, but you know that they will definitely be returned.

If you code your destructor to release resources not automatically released from an object, then you will never experience an issue with leaking resources out of your application.

When resources leak out of an application, they are lost and not recovered.

Chapter 10 – Advanced Object-Oriented Programming

Page 37: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

37

Releasing Allocated MemoryThe developer must handle reference type objects.

A developer decides when to create them, when and how to use them, and also when to release them.

If these resources aren’t released, it can lead to problems ranging from sluggish performance to a system crash.

Releasing memory can be accomplished in the code.

When you no longer need to access the reference type object, you must manually return the memory to the heap.

To deallocate or dereference an object, set the object name equal to the keyword Nothing, as in the following syntax:

Chapter 10 – Advanced Object-Oriented Programming

ObjectName = Nothing

If you wanted to deallocate the text box txtName from the previous example, you would use the following code:

txtName = Nothing

Page 38: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

38

Coding a DestructorA destructor method is called Finalize.

The Finalize method should never be called directly.

The only routine that will call Finalize is the garbage collector itself.

The Finalize method may not be the only Finalize method called for a specific object.

When an object is created from another object using inheritance, a Finalize method may be called for each level of inheritance in the object.

The Finalize method is declared as Protected in scope and it must override the base method.

Chapter 10 – Advanced Object-Oriented Programming

Protected Overrides Sub Finalize() 'Code to release resources goes here MyObject = Nothing 'Deallocate an object you created

'Close a file if you had opened it during the execution of the object StreamReaderName.Close() FileStreamName.Close()End Sub

Page 39: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

39

Coding a Destructor ContinuedIf a separate Finalize method is coded for both the base and derived class, then when an object is created from the derived class, the Finalize method of the base class will be skipped.

In order to ensure that the Finalize method of a base class is called, you should code your Finalize methods as follows:

Chapter 10 – Advanced Object-Oriented Programming

Protected Overrides Sub Finalize() 'Code to release resources goes here MyBase.Finalize() 'Calls the base class' Finalize methodEnd Sub

Page 40: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

40

10.5 Case Study

Problem DescriptionUsers might want to track a project number that an employee was working on.

This would require a change to the grid and an additional text box and label to the form created in the case study of Chapter 7.

You could change the original application or you could create a new form that inherits most of its functionality from the original form:

Chapter 10 – Advanced Object-Oriented Programming

Page 41: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

41

Problem DiscussionYou should be able to create the inherited form from the base form, add the text box and label to the form, add a few lines of code, and be done, right? Not exactly.

Your new grid must have an additional column.

An inherited control cannot be modified in the IDE from the derived form.

You must change the number of columns programmatically.

The best place to accomplish this is in the constructor of the form.

You need to modify the code for the Click event of the frmAddEmployee button in the base class, but you are not allowed to modify the code of an event in the base class.

The code in the base class adds all of the individual employee’s values to the grid.

While all that is required is adding the code to copy the project number to the grid, you cannot override events with inheritance.

If you want code in an event to be inherited, you should place it in a subroutine that is overridable.

Place the code to initialize the grid in a subroutine called ProcessAdd.

The code to calculate the total payroll will not change.

Chapter 10 – Advanced Object-Oriented Programming

Page 42: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

42

Problem SolutionThe only changes to the base form are to move the code from the btnAddEmployee Click event to a subroutine ProcessAdd.

Chapter 10 – Advanced Object-Oriented Programming

Private Sub btnAddEmployee_Click(... ProcessAdd()End Sub

Public Overridable Sub ProcessAdd() grdEmployees.Rows = grdEmployees.Rows + 1

grdEmployees.Row = grdEmployees.Rows - 1

grdEmployees.Col = 0 grdEmployees.Text = grdEmployees.Rows - 1

grdEmployees.Col = 1 grdEmployees.Text = txtEmployee.Text

grdEmployees.Col = 2 grdEmployees.Text = txtHours.Text

grdEmployees.Col = 3 grdEmployees.Text = cmoDepartment.Text

grdEmployees.Col = 4

Page 43: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

43

Problem Solution ContinuedProcessAdd method continued:

Chapter 10 – Advanced Object-Oriented Programming

'First Week’s Calculations Select Case cmoDepartment.Text

Case "Sales" grdEmployees.Text = (Val(txtHours.Text) * _

intSalesPayRate).ToStringCase "Processing" grdEmployees.Text = (Val(txtHours.Text) * _

intProcessingPayRate).ToStringCase "Management" grdEmployees.Text = (Val(txtHours.Text) * _

intManagementPayRate).ToStringCase "Phone" grdEmployees.Text = (Val(txtHours.Text) * _

intPhonePayRate).ToString End SelectEnd Sub

Page 44: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

44

Problem Solution ContinuedCreate a form, frmCompletePayroll, as an inherited form from frmPayroll.

Add the following code to frmCompletePayroll constructor:

Chapter 10 – Advanced Object-Oriented Programming

'Add any initialization after the InitializeComponent() callgrdEmployees.Cols = 6grdEmployees.Row = 0grdEmployees.Col = 5grdEmployees.Text = "Project Number"

Page 45: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

45

Problem Solution ContinuedThe only other code required is to override the ProcessAdd subroutine to call the original ProcessAdd of the base form as well as processing the addition of the project number.

Chapter 10 – Advanced Object-Oriented Programming

Public Overrides Sub ProcessAdd() MyBase.ProcessAdd() grdEmployees.Col = 5 grdEmployees.Text = txtProjectNumber.TextEnd Sub

Page 46: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

46

Coach’s Corner

Additional EventsVisual Basic .NET’s strength lies in the inherent ease of creating interactive applications.

An interactive application must have the capability to respond to the user’s actions in a robust manner. Visual Basic .NET responds to a user’s actions by processing events.

Visual Basic .NET has many predefined events that allow the programmer to attach code to be executed when an event occurs.

A Click event occurs when the user clicks on the control.

The code associated with the event is executed. The Click event is usually the most frequently used event; however, there are many more.

Visual Basic .NET also allows you to create your own events.

Chapter 10 – Advanced Object-Oriented Programming

Page 47: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

47

Leave Event and Focus MethodData validation is a key concept in robust applications.

One could wait until all the data has been entered to check to see if the data entered is correct, or one can attach a Leave event to the controls for which you wish data validation to occur.

Leave is an event that is triggered when a control loses the current focus of the application.

Observe the following example that would check the txtDepartment text box to see if the value entered is Management, Sales, Processing, or Phone.

First you must select the txtDepartment text box from the object list box, as shown here:

Chapter 10 – Advanced Object-Oriented Programming

Page 48: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

48

Leave Event and Focus Method ContinuedThen, because Leave is not the default event, you must select the Leave event from the Procedure list box:

Chapter 10 – Advanced Object-Oriented Programming

Page 49: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

49

Leave Event and Focus Method ContinuedAdd the validation code to the Leave event.

You need to check if the department entered is not equal to one of the valid ones.

If it is not, then a message is displayed warning the user that the value entered was not valid.

Chapter 10 – Advanced Object-Oriented Programming

Private Sub txtDepartment_Leave(ByVal sender As Object, _ByVal e As System.EventArgs) Handles txtDepartment.Leave

If (UCase(txtDepartment.Text) <> "MANAGEMENT") And _(UCase(txtDepartment.Text) <> "SALES") And _(UCase(txtDepartment.Text) <> "PROCESSING") And _(UCase(txtDepartment.Text) <> "PHONE") ThenMsgBox("Invalid Department Entered")

End IfEnd Sub

Page 50: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

50

Leave Event and Focus Method ContinuedYou have the capability to force the user to enter a valid value or not allow the user’s focus to leave the current control.

Using the Focus method, you can shift the focus of the application back to the control that has the invalid data.

Observe the rewritten Leave code for txtDepartment.

This code returns the focus of the application to txtDepartment when an invalid department is entered:

Chapter 10 – Advanced Object-Oriented Programming

Private Sub txtDepartment_Leave(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles txtDepartment.Leave

If (UCase(txtDepartment.Text) <> "MANAGEMENT") And _ (UCase(txtDepartment.Text) <> "SALES") And _ (UCase(txtDepartment.Text) <> "PROCESSING") And _ (UCase(txtDepartment.Text) <> "PHONE") Then

MsgBox("Invalid Department Entered")txtDepartment.Focus()

End IfEnd Sub

Page 51: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

51

MouseHover and MouseMove EventsVisual Basic .NET has many events related to the movement of the mouse over the object the event is coded for. Two simple events are MouseHover and MouseMove.

The MouseHover event will be called when the mouse pauses over an object that has a MouseHover event coded.

The MouseMove event will be called when the mouse moves over an object that has a MouseMove event coded.

Chapter 10 – Advanced Object-Oriented Programming

Page 52: The Visual Basic.NET Coach 1 Chapter 10 – Advanced Object-Oriented Programming Everything in Visual Basic.NET is considered an object. When everything

The Visual Basic .NET Coach

52

MouseHover and MouseMove Events ContinuedHere is the code:

Chapter 10 – Advanced Object-Oriented Programming

Private Sub txtMidtermGrade_MouseHover(ByVal sender As Object, _ByVal e As System.EventArgs) _Handles txtMidtermGrade.MouseHover

lblHelp.Text = "Enter the student’s midterm grade." & _ "The grade should be a value from 0 to 100."

End Sub

Private Sub txtMidtermGrade_MouseMove(ByVal sender As Object, _ByVal e As System.Windows.Forms.MouseEventArgs) _Handles txtMidtermGrade.MouseMove

lblHelp.Text = ""End Sub