76
Chapter 12, Slide 1 Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Embed Size (px)

Citation preview

Page 1: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 1 Starting Out with Visual Basic 3rd Edition

Chapter 12

Classes, Exceptions, Collections,

and Scrollable Controls

Page 2: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 2 Starting Out with Visual Basic 3rd Edition

Chapter 12Introduction

Page 3: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 3 Starting Out with Visual Basic 3rd Edition

Chapter 12 Topics

Classes• Abstract Data Types• Objects, Properties, Methods

Exceptions Collections Object Browser Scrollable Controls

Page 4: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 4 Starting Out with Visual Basic 3rd Edition

Section 12.1Classes and Objects

Classes Are Program Structures That Define Abstract Data Types and Are Used to Create

Objects

Page 5: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 5 Starting Out with Visual Basic 3rd Edition

Abstract Data Types An abstract data type (ADT) is a data type

created by a programmer ADTs are important in computer science and

object-oriented programming An abstraction is a model of something that

includes only its general characteristics Dog is an abstraction

• Defines a general type of animal but not a specific breed, color, or size

• A dog is like a data type• A specific dog is an instance of the data type

Page 6: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 6 Starting Out with Visual Basic 3rd Edition

Classes

A class is a program structure that defines an abstract data type• Must create the class first• Then can create instances of the class

Class instances share common attributes VB forms and controls are classes

• Each control in the toolbox, is its own class• When you place a button on a form you’re

creating an instance of the button class• An instance is also called an object

Page 7: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 7 Starting Out with Visual Basic 3rd Edition

Properties, Methods, and Events

Programs communicate with an object using the properties and methods of the class

Class properties example: Buttons have Location, Text, and Name properties

Class methods example: The Focus method functions identically for every single button

Class event procedures: Each button in a form has a different click event procedure

Page 8: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 8 Starting Out with Visual Basic 3rd Edition

Object Oriented Design

The challenge is to design classes that effectively cooperate and communicate

Analyze program specifications to determine ADTs that best implement the specifications

Classes are fundamental building blocks• Typically represent nouns of some type

Page 9: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 9 Starting Out with Visual Basic 3rd Edition

Object Oriented Design Example

Specifications:We need to keep a list of students that lets us track the courses they have completed. Each student has a transcript that contains all information about his or her completed courses. At the end of each semester, we will calculate the grade point average of each student . At times, users will search for a particular course taken by a student.

Nouns from the specification above usually become classes in the program design

Verbs such as calculate GPA and search become methods of those classes

Page 10: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 10 Starting Out with Visual Basic 3rd Edition

OOD Class Characteristics

Class Attributes (properties) Operations (methods)

Student LastName, FirstName, Display, Input IdNumber

StudentList AllStudents, Count Add, Remove, FindStudent

Course Semester, Name, Display, InputGrade,Credits

Transcript CourseList, Count Display, Search,CalcGradeAvg

Page 11: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 11 Starting Out with Visual Basic 3rd Edition

Interface and Implementation

Class interface is the portion of the class visible to the application programmer

Class implementation is the portion of the class hidden from client programs• Private member variables• Private properties• Private methods

Hiding of all data and procedures inside a class is referred to as encapsulation

Page 12: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 12 Starting Out with Visual Basic 3rd Edition

Section 12.2Creating a Class

To Create a Class in Visual Basic, You Create a Class Declaration

The Class Declaration Specifies the Member Variables, Properties, Methods, and Events That Belong to the Class

Page 13: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 13 Starting Out with Visual Basic 3rd Edition

Class Declaration

ClassName is the name of the class Examples of MemberDeclarations are

presented in the following slides To create a new class:

• Clicking Add New Item button on toolbar• Select Class from Add New Item dialog box• Provide a name for the class and click Add• Adds a new, empty class file (.vb) to project

Public Class ClassNameMemberDeclarations

End Class

Page 14: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 14 Starting Out with Visual Basic 3rd Edition

Member Variables

A variable declared inside a class declaration Syntax:

AccessSpecifier may be Public or Private Example:

AccessSpecifer VariableName As DataType

Public Class StudentPublic strLastName As String ‘Student last namePublic strFirstName As String ‘Student first namePublic strId As String ‘Student ID number

End Class

Page 15: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 15 Starting Out with Visual Basic 3rd Edition

Creating an Instance of a Class

A two step process creates a class object Declare a variable whose type is the class

Create instance of class with New keyword and assign the instance to the variable

freshman defined here as an object variable Can accomplish both steps in one statement

Dim freshman As New Student()

freshman = New Student()

Dim freshman As Student

Page 16: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 16 Starting Out with Visual Basic 3rd Edition

Accessing Members

Can work with Public member variables of a class object in code using this syntax:

For example:• If freshman references a Student class object• And Student class has member variables

strFirstName, strLastName, and strID• Can store values in member variables with

freshman.strFirstName = "Joy"freshman.strLastName = "Robinson"freshman.strId = "23G794"

object.memberVariable

Page 17: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 17 Starting Out with Visual Basic 3rd Edition

Property Procedure

A property procedure is a function that behaves like a property

Controls access to property values Procedure has two sections: Get and Set

• Get code executes when value is retrieved• Set code executes when value is stored

Properties almost always declared Public to allow access from outside the class

Set code often provides data validation logic

Page 18: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 18 Starting Out with Visual Basic 3rd Edition

Property Procedure Syntax

Public Property PropertyName() As DataTypeGet

StatementsEnd GetSet(ParameterDeclaration)

StatementsEnd Set

End Property

Page 19: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 19 Starting Out with Visual Basic 3rd Edition

Property Procedure Example

Public Class Student' Member variablesPrivate sngTestAvg As Single

Public Property TestAverage() As SingleGet

Return sngTestAvgEnd GetSet(ByVal value As Single)

If value >= 0.0 And value <= 100.0 ThensngTestAvg = value

ElseMessageBox.Show( _

"Invalid test average.", "Error")End If

End SetEnd Property

End Class

Page 20: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 20 Starting Out with Visual Basic 3rd Edition

Setting and Validating a Property

TestAverage property is set as shown:

Passes 82.3 into value parameter of Set• If in the range 0.0 to 100.0, value is stored• If outside the range, message box displayed

instead of value being storedSet(ByVal value As Single)

If value >= 0.0 And value <= 100.0 ThensngTestAvg = value

ElseMessageBox.Show( _"Invalid test average.", "Error")

End IfEnd Set

Dim freshman as New Student()freshman.TestAverage = 82.3

Page 21: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 21 Starting Out with Visual Basic 3rd Edition

Read-Only Properties Useful at times to make a property read-only Allows access to property values but cannot

change these values from outside the class Use the ReadOnly keyword instead of Public

This causes the propertyName to be read-only -- not settable from outside of the class

ReadOnly Property PropertyName() As DataTypeGet

StatementsEnd Get

End Property

Page 22: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 22 Starting Out with Visual Basic 3rd Edition

Read-Only Property Example' TestGrade property procedureReadOnly Property TestGrade() As Char

GetIf sngTestAverage >= 90

return "A"Else If sngTestAverage >= 80

return "B"Else If sngTestAverage >= 70

return "C"Else If sngTestAverage >= 60

return "D"Else

return "F"End If

End GetEnd Property

Page 23: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 23 Starting Out with Visual Basic 3rd Edition

Object Removal & Garbage Collection Memory space is consumed when objects are

instantiated Objects no longer needed should be removed Set object variable to Nothing so it no longer

references the object

Variable is a candidate for garbage collection when it no longer references an object

The garbage collector runs periodically destroying objects no longer needed

freshman = Nothing

Page 24: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 24 Starting Out with Visual Basic 3rd Edition

Going Out of Scope

An object variable instantiated within a procedure is local to that procedure

An object goes out of scope when• Referenced only by local variables and• The procedure ends

Object removed once it goes out of scope An object instantiated in a procedure and

assigned to a global variable is not removed• Reference remains when procedure ends

Page 25: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 25 Starting Out with Visual Basic 3rd Edition

Going Out of Scope, Example

Sub CreateStudent()Dim sophomore As Studentsophomore = New Student()sophomore.FirstName = "Travis"sophomore.LastName = "Barnes"sophomore.IdNumber = "17H495"sophomore.TestAverage = 94.7g_studentVar = sophomore

End Sub

With this statement, sophomore will not go out of scope.Without this statement, it will go out of scope when the procedure ends. (g_studentVar is a module-level variable.)

Page 26: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 26 Starting Out with Visual Basic 3rd Edition

Comparing Object Variables

Multiple variables can reference the same object

Can test if two variables refer to same object• Must use the Is operator

• The = operator cannot be used to test for this

Dim collegeStudent As StudentDim transferStudent As StudentcollegeStudent = New Student()transferStudent = collegeStudent

If collegeStudent Is transferStudent Then' Perform some action

End If

Page 27: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 27 Starting Out with Visual Basic 3rd Edition

IsNot & Nothing Object Comparisons

Use the IsNot operator to determine that two variables do not reference the same object

Use the special value Nothing to determine if a variable has no object reference

If collegeStudent IsNot transferStudent Then' Perform some action

End If

If collegeStudent Is Nothing Then' Perform some action

End If

Page 28: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 28 Starting Out with Visual Basic 3rd Edition

Can create an entire array of object variables• Declare an array whose type is a class• Instantiate an object for each element

Creating an Array of Objects

' Declare the arrayDim mathStudents(9) As StudentDim i As IntegerFor i = 0 To 9

' Assign each element to an objectmathStudents(i) = New Student()

Next i

Page 29: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 29 Starting Out with Visual Basic 3rd Edition

Can use object variables as arguments to a sub or function• Example: student object s as an argument

Pass object variable with the procedure call

Objects As Procedure Arguments

Sub DisplayStudentGrade(ByVal s As Student)' Displays a student’s grade.MessageBox.Show("The grade for " & _

s.FirstName & " " & s.LastName & _" is " & s.TestGrade.ToString)

End Sub

DisplayStudentGrade(freshman)

Page 30: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 30 Starting Out with Visual Basic 3rd Edition

Objects Passed ByVal and ByRef

If argument is declared using ByRef• Values of object properties may be changed• The original object variable may be assigned

to a different object If argument is declared using ByVal

• Values of object properties may be changed• The original object variable may not be

assigned to a different object

Page 31: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 31 Starting Out with Visual Basic 3rd Edition

Functions Can Return Objects

Dim freshman As Student = GetStudent()…Function GetStudent() As Student

Dim s As New Student()s.FirstName = InputBox("Enter the first name.")s.LastName = InputBox("Enter the last name.")s.IdNumber = InputBox("Enter the ID number.")s.TestAverage = InputBox("Enter the test average.")Return s

End Function

Example below instantiates a student object Prompts for and sets its property values Then returns the instantiated object

Page 32: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 32 Starting Out with Visual Basic 3rd Edition

Class Methods

In addition to properties, a class may also contain sub and function procedures

Methods are procedures defined in a class Typically operate on data stored in the class The following slide shows a Clear method for

the Student class• Method called with freshman.Clear()• Method clears member data in the Student

class object referenced by freshman

Page 33: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 33 Starting Out with Visual Basic 3rd Edition

Clear Method for Student ClassPublic Class Student

' Member variablesPrivate strLastName As String 'Holds last namePrivate strFirstName As String 'Holds first namePrivate strId As String 'Holds ID numberPrivate sngTestAverage As Single 'Holds test avg

(...Property procedures omitted...)

' Clear methodPublic Sub Clear()

strFirstName = String.EmptystrLastName = String.EmptystrId = String.EmptysngTestAverage = 0.0

End SubEnd Class

Page 34: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 34 Starting Out with Visual Basic 3rd Edition

Constructors A constructor is a method called automatically

when an instance of the class is created Think of constructors as initialization routines Useful for initializing member variables or

performing other startup operations To create a constructor, simply create a Sub

procedure named New within the class Next slide shows a Student class constructor

• The statement freshman = New Student() • Creates an instance of the Student class• Executes constructor to initialize properties of

the Student object referenced by freshman

Page 35: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 35 Starting Out with Visual Basic 3rd Edition

Constructor ExamplePublic Class Student

' Member variablesPrivate strLastName As String 'Holds last namePrivate strFirstName As String 'Holds first namePrivate strId As String 'Holds ID numberPrivate sngTestAverage As Single 'Holds test avg

' ConstructorPublic Sub New()

strFirstName = "(unknown)"strLastName = "(unknown)"strId = "(unknown)"testAvg = 0.0

End Sub

(The rest of this class is omitted.)End Class

Page 36: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 36 Starting Out with Visual Basic 3rd Edition

Create a Class

Tutorial 12-1 demonstrates code needed to set up for the Student class

Page 37: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 37 Starting Out with Visual Basic 3rd Edition

Section 12.3Collections

A Collection Holds a Group of Items

It Automatically Expands and Shrinks in Size to Accommodate the Items Added to It, and Allows Items to Be Stored With Associated

Key Values, Which May Be Used in Searches

Page 38: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 38 Starting Out with Visual Basic 3rd Edition

Collections A collection is similar to an array A single unit that contains several items Can access items in a collection by numeric

index A collection’s indices begin at one, not zero Collections automatically expand and shrink

as items are added and removed The items stored in a collection do not have

to be of the same type

Page 39: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 39 Starting Out with Visual Basic 3rd Edition

A Collection is a Class

New collections are instantiations of the Collection Class

The Collection Class provides various methods and properties for use with individual collections

Dim customers As Collectioncustomers = New Collection()

' Or alternatively

Dim customers As New Collection()

Page 40: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 40 Starting Out with Visual Basic 3rd Edition

Adding Items to a Collection

Add is a method of the Collection class Object is the collection that Item is added to Item can be an object, variable, or value Key is a unique value optionally used to

identify a member of the collection Before or After is used to specify where a

new item should be placed in the collection Default is to insert at the end of the collection

Object.Add(Item [, Key] [, Before] [,After])

Page 41: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 41 Starting Out with Visual Basic 3rd Edition

Uses of Before and After

Add custData with key "Smith" before the item with key "Thomas“

Add custData with key "Smith" after the item with key "Reece“

Add custData after 3rd item in collection

customers.Add(custData, "Smith", "Thomas")

customers.Add(custData, "Smith",, "Reece")

customers.Add(custData,,,3)

Page 42: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 42 Starting Out with Visual Basic 3rd Edition

Add Method Exceptions An exception can occur when adding to a

collection so Try-Catch should be used• Cannot add member with same key as

another member of the collection• If a key or index is specified for a Before or

After, the value must exist

Trycustomers.Add(custData, "Smith")

Catch ex as ArgumentExceptionMessageBox.Show(ex.Message)

End Try

Page 43: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 43 Starting Out with Visual Basic 3rd Edition

Accessing Item by Their Indices

Can access an item in a collection using an index value

Index value can be used in two ways:• Using the collection’s Item method

• Or specify the index as is done with an array

Get value at index 3 of names collection by:names.Item(3) –or- names(3)

Object(Index)

Object.Item(Index)

Page 44: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 44 Starting Out with Visual Basic 3rd Edition

IndexOutOfRange Exception

If an invalid index is encountered, an index out of range exception will occur

Should use Try-Catch to trap such messages

Dim custData as CustomerTry

custData = Ctype(customers.Item(5), Customer)Catch ex as IndexOutOfRangeException

MessageBox.Show(ex.Message)End Try

Page 45: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 45 Starting Out with Visual Basic 3rd Edition

The Count Property

The Count property of a collection gives the number of current items in the collection

Dim intX As IntegerFor intX = 1 To names.Count

lstNames.Items.Add(names(intX).ToString())Next intX

Page 46: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 46 Starting Out with Visual Basic 3rd Edition

Storing Objects in a Collection

Storing an object, without a key

Storing an object, with a key

Dim studentCollection As New Collection()

studentCollection.Add(studentData)

studentCollection.Add(studentData, _studentData.IdNumber)

Page 47: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 47 Starting Out with Visual Basic 3rd Edition

Searching for an Item by Key Value Item method can be used to retrieve an item

with a specific index

If Expression is a string, it is used as a key to search for the matching member

If Expression is numeric, it is used as an index value for the item

If no item is found (via key or index), an exception occurs

Object.Item(Expression)

Page 48: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 48 Starting Out with Visual Basic 3rd Edition

Retrieving Item Examples Find studentCollection item with key 49812

• If Option Strict on, must cast result to Student

Retrieve all members by index and display LastName property in a message box

Dim s as Students = Ctype(studentCollection.Item(“49812”), Student)

Dim i as IntegerDim s as StudentFor I = 1 to studentCollection.Count

s = Ctype(studentCollection.Item(i), Student)MessageBox.Show(s.LastName)

Next i

Page 49: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 49 Starting Out with Visual Basic 3rd Edition

Using References Versus Copies

When an Item in a collection is a fundamental VB data type, only a copy is retrieved• This code does not change the item at index 1

The Item in this collection is an object so:• A reference is returned instead of a copy• LastName of object in collection is changedDim s as Students = CType(studentCollection.Item("49812"), Student)s.LastName = "Griffin"

Dim n as Integern = CType(numbers(1), Integer)n = 0

Page 50: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 50 Starting Out with Visual Basic 3rd Edition

For Each Loop with a Collection

Dim s As StudentFor Each s In studentCollection

MessageBox.Show(s.LastName)Next s

Can use a For Each loop to read members of a collection• Eliminates the counter variable required to

use a For…Next • Also no need to compare to Count property

Page 51: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 51 Starting Out with Visual Basic 3rd Edition

Removing Members of a Collection

Remove is a method of the Collection class Object is collection Member removed from Expression can be

• Numeric and interpreted as an index• Or a string and interpreted as a key value• Exception thrown if Expression not found

Object.Remove(Expression)

Page 52: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 52 Starting Out with Visual Basic 3rd Edition

Removing Member Examples

Verify “49812” is a key value in collection, then remove member with this key value

Verify index location 7 exists in collection, then remove member at this index location

If studentCollection.Contains(“49812”) ThenstudentCollection.Remove("49812")

End If

Dim intIndex As Integer = 7If intIndex > 0 _

and intIndex <=studentCollection.Count ThenstudentCollection.Remove(intIndex)

End If

Page 53: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 53 Starting Out with Visual Basic 3rd Edition

Working with Collections

Since a collection is an instance of a class• Procedures accept collections as arguments• Functions can return a collection• Follow same guidelines as any class object

Parallel collections work like parallel arrays• Can use index to relate parallel collections

just as we did with arrays• Or can use key values to relate collections

Page 54: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 54 Starting Out with Visual Basic 3rd Edition

Section 12.4The Student Collection

Application

Create an Application that Uses a Collection of Student Objects

Page 55: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 55 Starting Out with Visual Basic 3rd Edition

Section 12.5The Object Browser

The Object Browser Is a Dialog Box That Allows You to Browse All Classes and Components That Are Available to

Your Project

Page 56: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 56 Starting Out with Visual Basic 3rd Edition

Working with Collections

A dialog box with information about objects Allows you to examine

• Information about forms in your project• Classes you’ve created• Other components used by VB in your project

Tutorial 12-3 uses the Object Browser to examine the Student Collection project

Page 57: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 57 Starting Out with Visual Basic 3rd Edition

Object Browser, Example

Page 58: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 58 Starting Out with Visual Basic 3rd Edition

Section 12.6Scroll Bars and Track Bars

The HScrollBar, VScrollBar, and TrackBar Controls Provide a Graphical Way to Adjust a Number Within a Range of Values

Page 59: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 59 Starting Out with Visual Basic 3rd Edition

Visual Appearance and Usage

The HScrollBar and VScrollBar look like normal scroll bars

The TrackBar has an arrow pointer as the slider and has tick marks along its length

Scrollable controls hold integers in their Value property• Position of slider corresponds to Value• Move scroll bar to increase or decrease Value• Right increases, left decreases horizontal bar• Up increases, down decreases vertical bar

Page 60: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 60 Starting Out with Visual Basic 3rd Edition

Scrollable Control Properties Minimum – the bar’s lowest possible value Maximum – the bar's highest possible value Value – the bar's value at the current position LargeChange – change in the Value property

with a mouse click on/near the slider SmallChange – change in the Value property

for amouse click on an arrow at the end TickFrequency - for TrackBar only, the

number of units between tick marks• With min=0 and max=1000, if Tick Frequency is 100,

10 tick marks are shown on the bar

Page 61: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 61 Starting Out with Visual Basic 3rd Edition

Coding for Scrollable Controls Any change to the position of a scroll bar

generates a Scroll event• Allows program to react to a shift in scroll bar

Standard prefixes for these controls• Horizontal scroll bar is hsb• Vertical scroll bar is vsb• TrackBar is tb

Tutorial 12-4 demonstrates how to set up Scroll events and use of these controls

Page 62: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 62 Starting Out with Visual Basic 3rd Edition

Section 12.7Introduction to Inhertance

Inheritance Allows a New Class to be Based on an Existing Class

The New Class Inherits the Accessible Member Variables, Methods, and Properties of the Class on Which It Is Based

Page 63: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 63 Starting Out with Visual Basic 3rd Edition

Why Inheritance? Inheritance allows new classes to derive

their characteristics from existing classes The Student class may have several types of

students such as• GraduateStudent• ExchangeStudent• StudentEmployee

These can become new classes and share all the characteristics of the Student class

Each new class would then add specialized characteristics that differentiate them

Page 64: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 64 Starting Out with Visual Basic 3rd Edition

Base and Derived Classes

The Base Class is a class that other classes may be based on

A Derived Class is based on the base class and inherits characteristics from it

Can think of the base class as a parent and the derived class as a child

Page 65: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 65 Starting Out with Visual Basic 3rd Edition

The Vehicle Class (Base Class) Consider a Vehicle class with the following:

• Private variable for number of passengers• Private variable for miles per gallon• Public property for number of passengers

(Passengers)• Public property for miles per gallon

(MilesPerGallon) This class holds general data about a vehicle Can create more specialized classes from

the Vehicle class

Page 66: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 66 Starting Out with Visual Basic 3rd Edition

The Truck Class (Derived Class) Declared as:

Truck class derived from Vehicle class • Inherits all non-private methods, properties,

and variables of Vehicle class Truck class defines two properties of its own

• MaxCargoWeight – holds top cargo weight• FourWheelDrive – indicates if truck is 4WD

Public Class TruckInherits Vehicle' Other new properties' Additional methods

End Class

Page 67: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 67 Starting Out with Visual Basic 3rd Edition

Instantiating the Truck Class Instantiated as:

Values stored in MaxCargoWeight and FourWheelDrive properties • Properties declared explicitly by Truck class

Values also stored in MilesPerGallon and Passengers properties • Properties inherited from Vehicle class

Dim pickUp as New Truck()pickUp.Passengers = 2pickUp.MilesPerGallon = 18pickUp.MaxCargoWeight = 2000Pickup.FourWheelDrive = True

Page 68: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 68 Starting Out with Visual Basic 3rd Edition

Overriding Properties and Methods

Sometimes a base class property procedure or method does not work for a derived class• Can override base class method or property • Must write the method or property as desired

in the derived class using same name When an object of the derived class

accesses the property or calls the method• VB uses overridden version in derived class • Version in base class is not used

Page 69: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 69 Starting Out with Visual Basic 3rd Edition

Property Override Example

Vehicle class has no restriction on number of passengers

But may wish to restrict the Truck class to two passengers at most

Can override Vehicle class Passengers property by:• Coding Passengers property in derived class• Specify Overridable in base class property• Specify Overrides in derived class property

Page 70: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 70 Starting Out with Visual Basic 3rd Edition

Overridable Base Class Property

Public Overridable Property Passengers() As IntegerGet

Return intPassengersEnd GetSet(ByVal value As Integer)

intPassengers = valueEnd Set

End Property

Overridable keyword added to base class property procedure

Page 71: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 71 Starting Out with Visual Basic 3rd Edition

Overridden Derived Class Property

Public Overrides Property Passengers() As Integer Get

Return MyBase.Passengers End Get Set(ByVal value As Integer)

If value >= 1 And value <= 2 Then MyBase.Passengers = valueElse MessageBox.Show("Passengers must be 1 or 2", _

"Error")End If

End SetEnd Property

Overrides keyword and new logic added to derived class property procedure

Page 72: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 72 Starting Out with Visual Basic 3rd Edition

Overriding Methods

Public Overridable Sub ProcedureName()

Public Overridable Function ProcedureName() As DataType

Public Overrides Sub ProcedureName()

Public Overrides Function ProcedureName() As DataType

Overriding a method is similar to a property Specify Overridable and Overrides keywords An overridable base class method

An overriding derived class method

Page 73: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 73 Starting Out with Visual Basic 3rd Edition

Overriding the ToString Method

Every programmer created class is derived from a built-in class named Object

Object class has a method named ToString which returns a fully-qualified class name

Method can be overridden to return a string representation of data stored in an object

Page 74: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 74 Starting Out with Visual Basic 3rd Edition

ToString Override Example

' Overriden ToString methodPublic Overrides Function ToString() As String

' Return a string representation' of a vehicle.Dim str As String

str = "Passengers: " & numPassengers.ToString & _" MPG: " & mpg.ToString

Return strEnd Function

Object class ToString method is Overridable Vehicle class might override the ToString

method as shown below

Page 75: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 75 Starting Out with Visual Basic 3rd Edition

Base & Derived Class Constructors

A constructor (named New) may be defined for both the base class and a derived class

When a new object of the derived class is created, both constructors are executed• The constructor of the base class will be

called first• Then the constructor of the derived class will

be called

Page 76: Chapter 12, Slide 1Starting Out with Visual Basic 3 rd Edition Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

Chapter 12, Slide 76 Starting Out with Visual Basic 3rd Edition

Protected Members

In addition to Private and Public, the access specifier may be Protected• Protected base class members are treated as

public to classes derived from this base• Protected base class members are treated as

private to classes not derived from this base

Tutorial 12-5 provides an opportunity to work with base and derived classes