You are on page 1of 171

Copyright © 2014 Pearson Education, Inc.

Chapter 12

Classes,
Collections, and
Inheritance

Copyright © 2014 Pearson Education, Inc. 1


Topics
• Topics
– 12.1 Classes and Objects
– 12.2 Creating a Class
– 12.3 Collections
– 12.4 Focus on Problem Solving: Creating the
Student Collection Application
– 12.5 Object Browser
– 12.6 Introduction to Inheritance

Copyright © 2014 Pearson Education, Inc. 2


Initial Exercise
• Create a VB Windows application with
– Controls
• Labels: first name, last name, age
• Text Boxes: first name, last name, age
• Buttons: submit, clear, exit

Copyright © 2014 Pearson Education, Inc. 3


12.1

Classes and Objects

Copyright © 2014 Pearson Education, Inc. 4


Object-Oriented Programming
• Object-oriented programming (OOP)
– Designing and coding applications with
interchangeable software
– First languages appeared in 1980’s
• SmallTalk, C++, ALGOL
– Examples of objects
• Form, button, check box, list box

Copyright © 2014 Pearson Education, Inc. 5


Classes and Objects
• Classes
– Program structures define abstract data types
– Used to define objects

Copyright © 2014 Pearson Education, Inc. 6


Abstract Data Types
• Abstract Data Type (ADT)
– Data type created by a programmer
– Important in computer science and object -
oriented programming (OOP)
– Abstraction is model of something in general
terms
• Definition includes general characteristics of object

Copyright © 2014 Pearson Education, Inc. 7


Abstract Data Types (cont.)
– Example
• Dog is an abstraction
– Defines a general type of animal but not a specific breed,
color, or size
• Lassie is an instance

Copyright © 2014 Pearson Education, Inc. 8


Classes
• Class
– Program structure defining abstract data
type
– Steps
• Design class first
• Then design a class client that creates an
instance of class

Copyright © 2014 Pearson Education, Inc. 9


Class Instances
• Each class instance or object
– Shares common characteristics/attributes
– Example
• In Visual Basic, Forms and Controls have classes
• In Toolbox, each icon represents a class
• Dragging a control (i.e. TextBox) from the toolbox
to a form creates an instance of a class (text box)

Copyright © 2014 Pearson Education, Inc. 10


Properties, Methods, and Events
• Programs communicate with an object using
– Class properties
• i.e. Button has Location, Text, and Name properties
– Class methods
• i.e. Focus( ) method functions identically for each
single button
– Class events
• i.e. Each button in a form has a different click event
procedure

Copyright © 2014 Pearson Education, Inc. 11


Object Oriented Design
• Object Oriented Design (OOD)
– Takes program specifications
– Analyzed specifications
– Determines ADTs to implement specifications
• In general
– Classes will be nouns
– Methods will be verbs

Copyright © 2014 Pearson Education, Inc. 12


Object Oriented Design (cont.)
– Designs classes to effectively cooperate and
communicate
– Creates a well-designed class to outlive an
application
• Other uses for the class may be found

Copyright © 2014 Pearson Education, Inc. 13


Finding the Classes
• Object-oriented analysis
– Starts with a detailed specification of problem
to be solved
• Known as finding the classes

Copyright © 2014 Pearson Education, Inc. 14


Object Oriented Design Example
• Program specification
– We want to schedule classes for students,
using the college's master schedule to
determine the times and room numbers for
each student's class. When the optimal
arrangement of classes for each student has
been determined, each student's class
schedule will be printed and distributed.

Copyright © 2014 Pearson Education, Inc. 15


Looking for Control Structures
• Controlling agent
– Could be implemented with a class (user
defined data type)
• Example
– Class called Scheduler
» Can be used to match each student’s schedule with
college’s master schedule

Copyright © 2014 Pearson Education, Inc. 16


OOD Class Characteristics
• Describe classes
– Attributes are implemented as properties
• Characteristics of each object
• Describe common properties of class objects
– Operations are implemented as methods
• Actions class objects perform
• Messages they can respond to

Copyright © 2014 Pearson Education, Inc. 17


OOD Class Characteristics
for Example

Copyright © 2014 Pearson Education, Inc. 18


Class Diagram for Example
• Class diagram for Student class
Student <- class name
- firstName : string
- lastName: string <- attributes (- private)
- Id : string
+ getFirstName( ) : string
+ setFirstName( value : string )
+ getLastName( ) : string <- methods (+ public)
+ setLastName( value : string )
+ getId( ) : string
+ setId( value : string )
+ New( )
+ New( pFirst : string, pLast : string, pId : string )
# Finalize( ) <- method (# protected)

Copyright © 2014 Pearson Education, Inc. 19


Interface and Implementation
• Class
– Interface
• Portion of class visible to application programmer
– Public member variables, properties, and methods
– Implementation
• Portion of class hidden from client programs
– Private member variables, properties, and methods
• Encapsulation
– Hiding data and methods inside a class

Copyright © 2014 Pearson Education, Inc. 20


Client Program
• Client program
– Uses class to
• Instantiate an object
• Access data members
• Call methods

Copyright © 2014 Pearson Education, Inc. 21


12.2

Creating a Class

Copyright © 2014 Pearson Education, Inc. 22


Class Declaration
• Class declaration
– Syntax
Public Class ClassName
MemberDeclarations
End Class

where
• ClassName is name of class
• MemberDeclarations are declarations for all
variables, constants, and methods that belong to
class

Copyright © 2014 Pearson Education, Inc. 23


Class Declaration (cont.)
– Example
Public Class Student
' …
End Class

Copyright © 2014 Pearson Education, Inc. 24


Creating a Class
• To create a new class
– Click Add New Item button on toolbar
– Select Class from Add New Item dialog box
– Provide a name for class
– Click Add
Adds a new, empty class file (.vb) to project

Copyright © 2014 Pearson Education, Inc. 25


Adding a Class

In Solution Explorer, right-click


on project then Add/Class…

Copyright © 2014 Pearson Education, Inc. 26


Specifying Class Name

Enter name of class (Person.vb)


Copyright © 2014 Pearson Education, Inc. 27
Person Class

Copyright © 2014 Pearson Education, Inc. 28


Member Declarations
• Member declarations
– Variables
– Constants
– Methods

Copyright © 2014 Pearson Education, Inc. 29


Member Variables
• Member variables
– Syntax
AccessSpecifer variableName As DataType
where
AccessSpecifier determines accessibility of variable
– Public access outside class or assembly
– Friend access only by other classes inside same
assembly
– Private access only by statements inside class
declaration
variableName is name of variable
DataType is variable’s data type

Copyright © 2014 Pearson Education, Inc. 30


Member Variables (cont.)
– Example
Public Class Student
Public LastName As String ' last name*
Public FirstName As String ' first name*
Public Id As String ' Id*
Public TestAverage As Double ' test average*
End Class

Note: Initially data members are Public, change to


Private after Property procedures are added

Copyright © 2014 Pearson Education, Inc. 31


Class Exercise 1
• Modify program with
– Controls
• Labels: first name, last name, age
• Text Boxes: first name, last name, age
• Buttons: submit, clear, exit
– Add a Person class
• Data members: first name,
last name, age

Copyright © 2014 Pearson Education, Inc. 32


Person Class with Members

Copyright © 2014 Pearson Education, Inc. 33


Class Instance
• To create instance of class in client
– Declare reference and create instance
Dim freshman As New Student()
– Declare reference and create instance
separately
Dim freshman As Student()
freshman = New Student()

Note: New allocates storage for instance


Copyright © 2014 Pearson Education, Inc. 34
Accessing Members
• To access members of instance of class
– Use "dot" notation
– Syntax
object.memberVariable
– Examples
freshman.FirstName = "Joy"
freshman.LastName = "Robinson"
freshman.Id = "23G794"

Copyright © 2014 Pearson Education, Inc. 35


Class Exercise 2
• Modify program with
– Controls
• Labels: first name, last name, age
• Text Boxes: first name, last name, age
• Buttons: submit, clear, exit
– Submit: Declare reference, create instance, populate
members from text boxes
– Add a person class
• Data members: first name, last name, age

Copyright © 2014 Pearson Education, Inc. 36


Class Exercise 2 - Code
Public Class Form1
Private Sub btnSubmit_Click(sender As Object,
e As EventArgs) Handles btnSubmit.Click
' create reference and instance of Person
class
Dim myPerson As New Person

myPerson.FirstName = txtFirstName.Text
myPerson.LastName = txtLastName.Text
Integer.Parse(txtAge.Text, myPerson.Age)
End Sub
End Class

Copyright © 2014 Pearson Education, Inc. 37


Property Procedure
• Property procedure
– Method that behaves like a property
– Controls access to property values
• Get - executes when value is retrieved
– May provide formatting
• Set - executes when value is stored
– May provide data validation logic
– Declared Public to allow access outside class

Copyright © 2014 Pearson Education, Inc. 38


Property Procedure (cont.)
– May be auto-implemented when no
processing is required for Get and Set

Copyright © 2014 Pearson Education, Inc. 39


Property Procedure Syntax
Public Property PropertyName() As DataType
Get
' Statements
End Get
Set(ParameterDeclaration)
' Statements
End Set
End Property

Copyright © 2014 Pearson Education, Inc. 40


Property Procedure Example
Public Class Student
' Member variable
Private _firstName As String ' Holds first name

Public Property FirstName() As String


Get
Return _firstName
End Get
Set(ByVal value As String)
_firstName = value.Trim()
End Set
End Property
End Class

Copyright © 2014 Pearson Education, Inc. 41


Insert Snippet

Copyright © 2014 Pearson Education, Inc. 42


Insert Snippet : Code Patterns

Copyright © 2014 Pearson Education, Inc. 43


Insert Snippet : Properties, etc.

Copyright © 2014 Pearson Education, Inc. 44


Insert Snippet : Define a Property

Copyright © 2014 Pearson Education, Inc. 45


Insert Snippet - Property

Copyright © 2014 Pearson Education, Inc. 46


Insert Snippet - Completed Property

Copyright © 2014 Pearson Education, Inc. 47


Property Procedure Example
Public Class Student
' Member variables
Private _firstName As String ' Holds first name
Private _testAvg As Double ' Holds test average

Public Property FirstName() As String


Get
Return _firstName
End Get
Set(ByVal value As String)
_firstName = value.Trim()
End Set
End Property

' additional properties

Copyright © 2014 Pearson Education, Inc. 48


Property Procedure Example (cont.)
Public Property TestAverage() As Double
Get
Return _testAvg
End Get
Set(ByVal value As Double) ' perform validation
If 0 <= value And value <= 100.0 Then
_testAvg = value
Else ' better not to use MessageBox in class
MessageBox.Show("Invalid average", "Error")
_testAvg = 0
End If
End Set
End Property
End Class

Copyright © 2014 Pearson Education, Inc. 49


Using Property Procedures Example
' in client

Dim freshman As New Student


' set properties
freshman.FirstName = "John"
freshman.LastName = "Doe"
freshman.Id = "1001"
freshman.TestAverage = 82.3

' use properties to get values


MessageBox.Show(freshman.FirstName & " " &
freshman.LastName & " earned " &
freshman.TestAverage.ToString())

Copyright © 2014 Pearson Education, Inc. 50


Class Exercise 3
• Modify program with
– Controls
• Labels: first name, last name, age
• Text Boxes: first name, last name, age
• Buttons: submit, clear, exit
– Submit: Declare reference, create instance, populate
Step 2 members from text boxes using property procedures
– Add a person class
• Data members: first name, last name, age
(make Private)
Step 1
• Public property procedures for data members
Copyright © 2014 Pearson Education, Inc. 51
Auto-Implemented Properties
• Auto-implemented property
– Class property defined by a single line of code
– VS automatically creates a hidden private
field (backing field) to hold the property value
– Does not include range checking or other
validations
– Can not be a ReadOnly property

Copyright © 2014 Pearson Education, Inc. 52


Auto-Implemented Properties
– Syntax
Public Property PropertyName As DataType
Public Property PropertyName As DataType = InitValue
– Examples
Public Property Salary As Decimal
Public Property Dependents As Integer = 1

Copyright © 2014 Pearson Education, Inc. 53


Sample Person.vb

Copyright © 2014 Pearson Education, Inc. 54


Sample Client

Copyright © 2014 Pearson Education, Inc. 55


Read-Only Properties
• ReadOnly property
– Causes property to be read-only
• Can not set using property
• Can not set from outside class
– Syntax
ReadOnly Property PropertyName() As DataType
Get
' Statements
End Get
End Property

Copyright © 2014 Pearson Education, Inc. 56


Read-Only Property Example 1
' TestGrade property procedure
Public ReadOnly Property TestGrade() As Char
Get
Dim letterGrade As Char
Select Case TestAverage
Case 90 To 100
letterGrade = "A"c ' character A
Case 80 To 90
letterGrade = "B"c
Case 70 To 80
letterGrade = "C"c
Case 60 To 70
letterGrade = "D"c
Case Else
letterGrade = "F"c
End Select
Return letterGrade
End Get
End Property
Read-Only Property Example 2
' Grade property procedure
Public ReadOnly Property Grade() As String
Get
Dim letterGrade As String
If TestAverage >= 90.0 Then
letterGrade = "A"
ElseIf TestAverage >= 80.0 Then
letterGrade = "B"
ElseIf TestAverage >= 70.0 Then
letterGrade = "C"
ElseIf TestAverage >= 60.0 Then
letterGrade = "D"
Else
letterGrade = "F"
End If
Return letterGrade
End Get
End Property
Class Exercise 4
• Modify program with
– Controls
– Add a person class
• Data members: first name, last name, age
• Property procedures for data members
• Readonly property procedure for minor (returns
True if under 21)

Copyright © 2014 Pearson Education, Inc. 59


Sample Person.vb with ReadOnly

Copyright © 2014 Pearson Education, Inc. 60


Storing Objects
• Object storage
– When instantiated
• Memory space is allocated
– When no longer needed
• Release memory
• Set object variable to Nothing
freshman = Nothing

Copyright © 2014 Pearson Education, Inc. 61


Garbage Collection
• Garbage Collector
– Runs periodically
– Destroys objects when no longer referenced
• When variable set to Nothing, it no longer
references an object
• When no variables reference an object, object is
eligible for garbage collection

Copyright © 2014 Pearson Education, Inc. 62


Going Out of Scope
• Scope
– Object instantiated within a method is local to
that method
– If object is only referenced by local variables,
object will be eligible for garbage collection
when method ends
• Called going out of scope

Copyright © 2014 Pearson Education, Inc. 63


Going Out of Scope (cont.)
– If object instantiated in a method is referenced
outside of method (by a global variable),
object will NOT be eligible for garbage
collection when method ends

Copyright © 2014 Pearson Education, Inc. 64


Going Out of Scope Example
Private aStudent As Student
Sub CreateStudent()
Dim sophomore As New Student()

sophomore.FirstName = "Travis"
sophomore.LastName = "Barnes"
Property procedure calls
sophomore.ID = "17H495"
sophomore.TestAverage = 94.7

aStudent = sophomore

End Sub
With this statement, 'sophomore' will not go out of scope.
Without this statement, it will go out of scope.
(aStudent is a class level variable)
Copyright © 2014 Pearson Education, Inc. 65
Comparing Objects
• When comparing objects
– Multiple variables may reference same object
– To determine if variables reference same
object
• Do NOT use equals (=) operator
• Use Is operator
– To determine if variables don't reference same
object
• Do NOT use not equals (<>) operator
• Use IsNot operator

Copyright © 2014 Pearson Education, Inc. 66


Is Operator
• Is operator
– Determines if two variables reference same
object
If collegeStudent Is transferStudent Then
' Perform some action
End If

Copyright © 2014 Pearson Education, Inc. 67


IsNot Operator
• IsNot operator
– Determines if two variables do not reference
same object
If collegeStudent IsNot transferStudent Then
' Perform some action
End If

Copyright © 2014 Pearson Education, Inc. 68


Nothing
• Nothing keyword
– Identifies no object reference

Copyright © 2014 Pearson Education, Inc. 69


Is Operator Examples
Dim collegeStudent As Student
Dim transferStudent As Student
collegeStudent = New Student()
transferStudent = collegeStudent

If collegeStudent Is transferStudent Then
' Perform some action
End If

If collegeStudent Is Nothing Then
' Perform some action (i.e. instantiate)
End If

Copyright © 2014 Pearson Education, Inc. 70


Creating an Array of Objects
• To create an array of object variables
– Declare array whose type is a class
– Instantiate an object for each element
– Example
' Declare the array
Dim mathStudents(9) As Student ' 10 elements
Dim index As Integer
For index = 0 To mathStudents.Length - 1
' Instantiate object and assign to element
mathStudents(index) = New Student()
Next index

Copyright © 2014 Pearson Education, Inc. 71


Releasing an Array of Objects
• To release an array of object variables
– Set each element of array to Nothing
– Example
Dim index As Integer
For index = 0 To mathStudents.Length - 1
' Set each element to Nothing
mathStudents(index) = Nothing
Next index

Copyright © 2014 Pearson Education, Inc. 72


Passing Objects ByVal and ByRef

• Passing an object with


– ByRef
• Values may be changed in original object
• Original object variable may be assigned to a
different object
– ByVal
• Values may be changed in original object
• Original object variable may NOT be assigned to a
different object

Copyright © 2014 Pearson Education, Inc. 73


Object as Parameter Example
' Method to display a student's grade (client)
Sub DisplayStudentGrade(ByVal aStudent As Student)

' Displays grade for Student aStudent


MessageBox.Show("The grade for " &
aStudent.FirstName & " " & aStudent.LastName &
" is " & aStudent.TestGrade.ToString())

End Sub

' Sample call to method defined above


DisplayStudentGrade(freshman)

Copyright © 2014 Pearson Education, Inc. 74


Object Return Example
' in client
Dim freshman As Student = GetStudent()

' Get student data and return object
Function GetStudent() As Student
Dim aStudent As New Student()

aStudent.FirstName = InputBox("Enter first name")


aStudent.LastName = InputBox("Enter last name")
aStudent.Id = InputBox("Enter ID")
aStudent.TestAverage =
Double.Parse(InputBox("Enter average"))

Return aStudent
End Function

Copyright © 2014 Pearson Education, Inc. 75


Class Methods
• Classes have
– Data members
– Class methods
• Perform some operation on data stored in class
• Are sub procedures and functions defined in a
class
• Written inside class declaration

Copyright © 2014 Pearson Education, Inc. 76


ToString( ) Method
• ToString( ) method
– Inherited from Object class
– Class overrides method to return a string
representation of data stored in class

Copyright © 2014 Pearson Education, Inc. 77


Student ToString() Method Example
Public Class Student
' Member variables
Private _lastName As String ' last name
Private _firstName As String ' first name
Private _id As String ' ID
Private _testAvg As Double ' test average
(...Property procedures appear here...)

' ToString() method uses Properties


Public Overrides Function ToString() As String
Dim message As String
message = FirstName & " " & LastName &
"'s average is " & TestAverage.ToString()
Return message
End Function
End Class ' Usage example follows
lblMessage.Text = freshman.ToString()
Copyright © 2014 Pearson Education, Inc. 78
Clear( ) Method
• Clear( ) method
– Class may define a clear method to reset data
stored in class

Copyright © 2014 Pearson Education, Inc. 79


Student Clear( ) Method Example
Public Class Student
' Member variables
Private _lastName As String ' last name
Private _firstName As String ' first name
Private _id As String ' Id
Private _testAvg As Double ' test average
(...Property procedures appear here...)

' Clear() method uses data members


Public Sub Clear()
_firstName = String.Empty
_lastName = String.Empty
_id = String.Empty
_testAvg = 0.0
End Sub
End Class ' Usage example follows
Copyright © 2014 Pearson Education, Inc.
freshman.Clear() 80
Constructors
• Constructor
– New() method
– Automatically called when instance is created
– Used for
• Initializing member variables
• Performing other startup operations
– To create, add sub procedure New to class

Copyright © 2014 Pearson Education, Inc. 81


Constructor Example
Public Class Student
' Member variables
Private _lastName As String ' last name
Private _firstName As String ' first name
Private _id As String ' Id
Private _testAvg As Double ' test average
(...Property procedures appear here...)

' Constructor uses property procedures


Public Sub New()
FirstName = "(unknown)"
LastName = "(unknown)"
Id = "(unknown)"
TestAverage = 0.0
End Sub
End Class
Copyright © 2014 Pearson Education, Inc. 82
Class Exercise 5
• Modify program with
– Controls
– Add a person class
• Data members: first name, last name, age
• Property procedures for data members
• Readonly property procedure for minor (under 21)
• Constructor: New() Sub procedure

Copyright © 2014 Pearson Education, Inc. 83


Overloaded Constructor Example
' Overloaded constructor uses property procedures
Public Sub New(ByVal pFirstName As String,
ByVal pLastName As String, ByVal pId As String,
ByVal pTestAverage As Double)
FirstName = pFirstName
LastName = pLastName
Id = pId
TestAverage = pTestAverage
End Sub

Copyright © 2014 Pearson Education, Inc. 84


Overloaded Constructor Call
Example
' in client
Dim freshman As Student = GetStudentData()

' Get student data and return object
Function GetStudentData() As Student
Dim aStudent As New Student(
txtFirstName.Text, txtLastName.Text,
txtId.Text, Double.Parse(txtTestAverage.Text))

Return aStudent
End Function

Copyright © 2014 Pearson Education, Inc. 85


Finalizers
• Finalizer
– Finalize() method automatically called
before instance of class destroyed

Note: Since garbage collector runs periodically, it is not


predictable when an object will be destroyed. Nor is it
predictable when (or if) Finalize() method will
execute.

Copyright © 2014 Pearson Education, Inc. 86


Finalizers (cont.)
– To add a Finalize() method
• Select Finalize from method name drop-down
list to let Visual Basic create the template
Protected Overrides Sub Finalize()
MyBase.Finalize()
' perform some action - release objects
End Sub
• Add code following MyBase.Finalize()

Copyright © 2014 Pearson Education, Inc. 87


Class Exercise 6
• Modify program with
– Controls
– Add a person class
• Data members: first name, last name, age
• Property procedures for data members
• Readonly property procedure for minor (under 21)
• Finalizer: Finalize( ) method

Copyright © 2014 Pearson Education, Inc. 88


Regions
• Region
– Provides grouping within source
– Often includes
• Private data members
• Public properties
• Constructors
• Methods
– Syntax
#Region "description"
#End Region

Copyright © 2014 Pearson Education, Inc. 89


XML Documentation
• XML Documentation
– Allows you to produce documentation for
project
– Add ''' before code to document
• Class
• Methods
– Syntax
'''

Copyright © 2014 Pearson Education, Inc. 90


XML Documentation Example
#Region "Public methods"
''' <summary>
''' ToString() returns state of object
''' </summary>
''' <returns>String representation of
object</returns>
''' <remarks></remarks>
Public Overrides Function ToString() As String
Dim message As String
message = "Name: " & FirstName & " " &
LastName & " is " & Age.ToString() &
" years old and Minor: " & Minor.ToString()
Return message
End Function
#End Region

Copyright © 2014 Pearson Education, Inc. 91


Output Window
• Output window
– Valuable debugging tool
– Display by
• Clicking View/Other Windows/ Output
• Pressing Ctrl + Alt + O key combination

Copyright © 2014 Pearson Education, Inc. 92


Displaying Debug Messages
• Displaying messages
– Program can write debugging information to
Output Window
• Usually displayed at bottom of Visual Studio
display
– If not, click View/Other Windows/Output to display
– Valuable debugging tool

Copyright © 2014 Pearson Education, Inc. 93


Displaying Debug Messages (cont.)
– Insert following in startup form's Load event to
enable
Debug.Listeners.Add(New ConsoleTraceListener())

– Write message to Output window


Debug.WriteLine(message)

Copyright © 2014 Pearson Education, Inc. 94


Debug.WriteLine Examples
' Constructor
Public Sub New()
' for academic purposes only
Debug.WriteLine("Creating Student object")

LastName = String.Empty
FirstName = String.Empty
Id = String.Empty
TestAverage = 0.0
End Sub

Protected Overrides Sub Finalize()


MyBase.Finalize()

' for academic purposes only


Debug.WriteLine("Destroying Student object")
End Sub
Copyright © 2014 Pearson Education, Inc. 95
12.3

Collections

Copyright © 2014 Pearson Education, Inc. 96


Collections
• Collection
– Holds group of items
– Automatically resizes as items are added or
removed
– Stores item with associated key value
– Allows search by key value

Copyright © 2014 Pearson Education, Inc. 97


Collection Characteristics
• Collection
– Similar to an array
– Single unit containing several items
– Items accessed with numeric index
– Index values begin at one (1)
– Automatically expands as items are added
and shrinks as items are removed
– Items need not have same data type

Copyright © 2014 Pearson Education, Inc. 98


Collection Class
• New Collection
– Instance of Collection class
• Provides methods and properties for use with
individual collections
– Syntax
Dim customers As Collection
customers = New Collection()

' Or

Dim customers As New Collection()

Copyright © 2014 Pearson Education, Inc. 99


Add( ) Method of Collection
• Add( ) method
– Adds item to collection*
CollectionName.Add(Item [, Key])
where
• CollectionName - variable referring to collection
• Item - object, variable, or value to add to collection
• Key - unique value identifies member of collection;
may be used to search for items

Copyright © 2014 Pearson Education, Inc. 100


Add( ) Method (cont.)
– Example
' declare collection
Private customers As New Collection

' add value into collection


customers.Add(myCustomer)
' add value with key to collection
customers.Add(myCustomer, myCustomer.Name)

Copyright © 2014 Pearson Education, Inc. 101


Add( ) Method Exceptions
• Add( ) method exceptions
– Causes
• Item has duplicate key value
– Example
Try
customers.Add(myCustomer, myCustomer.Name)
Catch ex As ArgumentException
MessageBox.Show(ex.Message, "Error Adding")
End Try

Copyright © 2014 Pearson Education, Inc. 102


Collection Exercise 1
• Modify program with
– Controls
– Events
• Form Load: Create a collection of people
• Add: add person to collection
– Add a person class

Copyright © 2014 Pearson Education, Inc. 103


Accessing Item by Index
• Item( ) method
– Accesses item by index
• i.e. position in collection
– Item is optional
– Returns object
– Syntax
' Access using Item method
Object.Item(Index)

' Alternative form (without Item method)


Object(Index)

Copyright © 2014 Pearson Education, Inc. 104


Accessing Item by Index (cont.)
– Example
' Get value at index 1 of collection
Dim myCustomer As Customer =
CType(customers.Item(1), Customer)

- or -
Dim myCustomer As Customer =
CType(customers(1), Customer)

MessageBox.Show("Name:" & myCustomer.Name,


"Customer Found")

Copyright © 2014 Pearson Education, Inc. 105


IndexOutOfRange Exception
• IndexOutOfRange exception
– Occurs when index used is not valid
– Examples
Try
Dim myCustomer As Customer
Dim index As Integer = Integer.Parse(txtNum.Text)
myCustomer = CType(customers.Item(index), Customer)
MessageBox.Show("Name:" & myCustomer.Name,
"Customer Found")
Catch ex As IndexOutOfRangeException
' occurs when index invalid
MessageBox.Show(ex.Message, "Range Error")
End Try

Copyright © 2014 Pearson Education, Inc. 106


IndexOutOfRange Exception (cont.)
Try
Dim myCustomer As Customer
Dim i As Integer = Integer.Parse(txtIndex.Text)
myCustomer = CType(customers(i), Customer)
MessageBox.Show("Name:" & myCustomer.Name,
"Customer Found")
Catch ex As InvalidCastException
MessageBox.Show(ex.Message, "Value Error")
Catch ex As IndexOutOfRangeException
MessageBox.Show(ex.Message, "Range Error")
Catch ex As Exception
MessageBox.Show(ex.ToString(), "Error")
End Try

Copyright © 2014 Pearson Education, Inc. 107


Collection Count Property
• Count property (of collection)
– Number of current items in collection
– Example
' names is collection
Dim index As Integer

' add names to list box


For index = 1 To names.Count
lstNames.Items.Add(names(index).ToString())
Next index

Copyright © 2014 Pearson Education, Inc. 108


Storing Objects in Collection
• To store class object in collection
– Example without key
Dim students As New Collection()

students.Add(studentData)
– Example with key
Dim students As New Collection()

students.Add(studentData, studentData.Id)

Copyright © 2014 Pearson Education, Inc. 109


Searching in Collection
• To search for item in collection*
– Syntax
CollectionName.Item(Expression)
where
CollectionName is name of a collection
Expression is string or numeric
– If string, search for member by key
– If numeric, use as index value for item sought
*Note: Exception occurs if no item found (via key or
index)
Copyright © 2014 Pearson Education, Inc. 110
Finding Item Example
• Example
– Find item in students with key 49812
• If Option Strict On, cast result to Student
Dim s As Student
s = CType(students.Item("49812"), Student)

Copyright © 2014 Pearson Education, Inc. 111


Retrieving Item Example
• Example
– Retrieve all members and display last names
Dim index As Integer
Dim s As Student
For index = 1 to students.Count
s = CType(students.Item(index), Student)
MessageBox.Show(s.LastName, "Student")
Next index

Copyright © 2014 Pearson Education, Inc. 112


References vs. Copies
• When Item is retrieved from Collection
– Copy is returned if Item is value type
– Example
Dim num As Integer
num = CType(numbers(1), Integer)
num = 0

Copyright © 2014 Pearson Education, Inc. 113


References vs. Copies (cont.)
• When Item is retrieved from Collection
– Reference is returned if Item is object
– Example
Dim s As Student
s = CType(students.Item("49812"), Student)
' Change LastName property of item 49812
' within collection
s.LastName = "Griffin"

Copyright © 2014 Pearson Education, Inc. 114


Using References vs. Copies
• When an item in a collection is
– A fundamental Visual Basic type
• Integer, String, Decimal, and so on
• Only a copy of the member is returned
• Its value cannot be changed
– A class object
• A reference to the object is returned
• Its value can be changed

Copyright © 2014 Pearson Education, Inc. 115


Loops and Collections
• May use For/Next Loop with Collection
– Requires counter in For/Next loop
– Compares counter to Count property
– Example
' display last name of each student
Dim index As Integer
Dim s As Student

For index = 1 To students.Count


s = CType(students(index), Student)
MessageBox.Show(s.LastName, "Student Name")
Next index
Copyright © 2014 Pearson Education, Inc. 116
Loops and Collections (cont.)
• Use For Each/Next Loop with
Collection
– Eliminates counter in For/Next loop
– Eliminates counter compare to Count property
– Example
' display last name of each student
Dim s As Student
For Each s In students
MessageBox.Show(s.LastName, "Student Name")
Next s

Copyright © 2014 Pearson Education, Inc. 117


Collection Exercise 2
• Modify program with
– Controls
– Events
• Form Load: Create a collection of people
• Add: add person to collection; list members of
collection using For Each/Next
– Add a person class

Copyright © 2014 Pearson Education, Inc. 118


Removing Members
• Use Remove( ) method
– To remove a member from a collection
• Exception thrown if member not found
– ArgumentException
– IndexOutOfRangeException

Copyright © 2014 Pearson Education, Inc. 119


Removing Members (cont.)
– Syntax
CollectionName.Remove(Expression)
where
CollectionName is name of a collection
Expression is string or numeric
– Numeric, used as index
– String, used as key

Copyright © 2014 Pearson Education, Inc. 120


Removing Members (cont.)
– Examples
' Removing with index
Dim index As Integer = 7
If index > 0 And index <= students.Count Then
students.Remove(index)
End If

' Removing with key with Try/Catch


Dim key As String = "46812"
Try
students.Remove(key)
Catch ex As ArgumentException
MessageBox.Show(ex.Message, "Remove Error")
End Try
Copyright © 2014 Pearson Education, Inc. 121
Removing Members (cont.)
' Removing with key and check for existence
Dim key As String = "46812"
If students.Contains(key) Then
students.Remove(key)
End If

Copyright © 2014 Pearson Education, Inc. 122


Methods that Use Collections
• Sub procedures and functions can accept
collections as arguments
– Remember that a collection is an instance of
a class
– Follow same guidelines as
• Passing a class object as an argument
• Returning a class object from a function

Copyright © 2014 Pearson Education, Inc. 123


Parallel Collections
• Parallel collections
– Work like parallel arrays
– To relate collections, can use
• Index
• Key values

Copyright © 2014 Pearson Education, Inc. 124


Parallel Collections (cont.)
Dim hoursWorked As New Collection ' hours worked
Dim payRates As New Collection ' pay rates
Dim grossPay As Decimal
Dim key As String = "55678"

hoursWorked.Add(40, key) ' Store hours using key


payRates.Add(12.5, key) ' Store rate, same key

' same key used to retrieve related data


grossPay = hoursWorked.Item(key) * payRate.Item(key)

Copyright © 2014 Pearson Education, Inc. 125


12.4
Focus on Problem Solving:
Creating Student Collection Application

Copyright © 2014 Pearson Education, Inc. 126


MainForm Form
• Main Form
– Displays list of student IDs in list box
– When student ID is selected, student data is
displayed in labels
– Add Student button
displays AddForm
– Remove button
removes student with
selected student ID
Copyright © 2014 Pearson Education, Inc. 127
AddForm Form
• Add student form
– Allows user to enter student data in text boxes
– Add button adds student data to collections

Copyright © 2014 Pearson Education, Inc. 128


12.5

The Object Browser

Copyright © 2014 Pearson Education, Inc. 129


Object Browser
• Object Browser
– Dialog box with information about objects in
project
– Allows you to examine
• Classes created in project
• Namespaces, classes, and other components
used by VB in project
– Use View/Object Browser menu item

Copyright © 2014 Pearson Education, Inc. 130


Object Browser Example

Person class selected Class members shown

Copyright © 2014 Pearson Education, Inc. 131


Object Browser Exercise
• With your project
– Use Object Browser to investigate project
• Identify
– Sub procedures and functions
– Private and public access
– Controls and variables
– Events

Copyright © 2014 Pearson Education, Inc. 132


12.6

Introduction to Inheritance

Copyright © 2014 Pearson Education, Inc. 133


Inheritance
• Inheritance
– Allows new class to be based on existing
class
– New class inherits accessible
• Member variables
• Methods
• Properties
from class based on

Copyright © 2014 Pearson Education, Inc. 134


Why Inheritance?
• Inheritance
– Allows new class to inherit (or derive)
characteristics of existing classes
– New class
• Shares all characteristics of base class
• Adds new characteristics

Copyright © 2014 Pearson Education, Inc. 135


Inheritance Example
• Example
– From Student class, create special student
types
• GraduateStudent
• ExchangeStudent
• StudentEmployee
– New classes
• Have characteristics of Student
• Have own characteristics

Copyright © 2014 Pearson Education, Inc. 136


What is 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

Copyright © 2014 Pearson Education, Inc. 137


Base and Derived Classes
• Class types
– Base class
• Class that other classes may be based on
– Derived class
• Based on base class
• Inherits characteristics from base class

Note: Base class is parent, and derived class is child

Copyright © 2014 Pearson Education, Inc. 138


Base and Derived Classes
• The Base Class is a general-purpose class that
other classes may be based on
– Think of the base class as the parent

• A Derived Class is based on the base class and


inherits characteristics from it
– Think of the derived class as the child

Copyright © 2014 Pearson Education, Inc. 139


Derived Class Example
• Create derived class
– Use Inherits keyword and base class name
– Add any needed properties and methods
Public Class ExchangeStudent Inherits Student
Dim country As String
' Other new properties
' Additional methods
End Class

Copyright © 2014 Pearson Education, Inc. 140


Vehicle Class (Base Class)
• Vehicle class
– Data members (Private)
• Variable for number of passengers
• Variable for miles per gallon
– Properties (Public)
• Property for Passengers
• Property for MilesPerGallon
– Class holds general data about vehicle
Note: Can create specialized classes from Vehicle class

Copyright © 2014 Pearson Education, Inc. 141


The Vehicle 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

Copyright © 2014 Pearson Education, Inc. 142


Truck Class (Derived Class)
• Truck class
– Declared as: Public Class Truck
Inherits Vehicle
' Other new properties
' Additional methods
End Class

– Derived from Vehicle class


• Inherits non-private methods, properties, variables
– Properties
• MaxCargoWeight – holds top cargo weight
• FourWheelDrive – indicates if truck is 4WD
Copyright © 2014 Pearson Education, Inc. 143
The Truck Derived Class
• 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

• The Vehicle Inheritance program in the Chapter 12


student sample programs folder contains the code for
the Vehicle and Truck classes

Copyright © 2014 Pearson Education, Inc. 144


Instantiating a Truck
– Instantiated as: Dim pickUp As New Truck()
pickUp.Passengers = 2
pickUp.MilesPerGallon = 18
pickUp.MaxCargoWeight = 2000
Pickup.FourWheelDrive = True

– Properties declared explicitly by Truck class


• MaxCargoWeight, FourWheelDrive
– Properties inherited from Vehicle class
• MilesPerGallon, Passengers

Copyright © 2014 Pearson Education, Inc. 145


Inheritance Exercise 1
• Create a program with
– Controls
• Labels: first name, last name, age, program
• Text Boxes: first name, last name, age, program
• Buttons: submit, clear, exit
– Student Class (inherits from Person)
• Data member: program of study
• Property procedure for program of study

Copyright © 2014 Pearson Education, Inc. 146


Overriding Properties and Methods
• Override a property or method
– When derived class needs a different
implementation of a property procedure or
method than base class
– Note
• Base class property procedure or method must be
overridable
• Derived class property procedure or method
overrides base class version with same name

Copyright © 2014 Pearson Education, Inc. 147


Overriding Properties and Methods
(cont.)
• When an object of derived class accesses
overridden property or calls overridden
method
– VB executes overridden version in derived
class instead of version in base class

Copyright © 2014 Pearson Education, Inc. 148


Overriding Properties and Methods
• Sometimes a base class property procedure or method
must work differently for a derived class
– You can override base class method or property
– You 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
– The overridden version in derived class is used
– The base class version is not used

Copyright © 2014 Pearson Education, Inc. 149


Overriding Procedure 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 keyword in base class
property
– Specify Overrides keyword in derived class
property

Copyright © 2014 Pearson Education, Inc. 150


Properties in Base Class
• Base class must explicitly allow overriding
Public Overridable Property PropertyName() As DataType
Get
' Statements
End Get
Set(ParameterDeclaration)
' Statements
End Set
End Property

Copyright © 2014 Pearson Education, Inc. 151


Properties in Derived Class
• Derived class must explicitly override
Public Overrides Property PropertyName() As DataType
Get
' Statements
End Get
Set(ParameterDeclaration)
' Statements
End Set
End Property

Copyright © 2014 Pearson Education, Inc. 152


Properties in Base Class Example
• Example
Public Overridable Property Passengers() As Integer
Get
Return intPassengers
End Get
Set(ByVal value As Integer)
intPassengers = value
End Set
End Property

Copyright © 2014 Pearson Education, Inc. 153


Overridable Property Procedure in the
Base Class Example
• Overridable keyword added to Vehicle base class
property procedure

Public Overridable Property Passengers() As Integer


Get
Return intPassengers
End Get
Set(ByVal value As Integer)
intPassengers = value
End Set
End Property

Copyright © 2014 Pearson Education, Inc. 154


Properties in Derived Class Example
• Example
Public Overrides Property Passengers() As Integer
Get
Return MyBase.Passengers
End Get
Set(ByVal value As Integer)
If 1 <= value AndAlso value <= 2 Then
MyBase.Passengers = value
Else
MessageBox.Show("Passengers must be 1 or 2", _
"Error")
End If
End Set
End Property
Copyright © 2014 Pearson Education, Inc. 155
Overridden Property Procedure in the
Derived Class Example
• Overrides keyword and new logic added to Truck derived class
property procedure
• The MyBase keyword refers to the base class
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 = value
Else
MessageBox.Show("Passengers must be 1 or 2.", "Error")
End If
End Set
End Property

Copyright © 2014 Pearson Education, Inc. 156


Overriding Sub Procedures and
Functions Syntax for Base Class
• Base class must explicitly allow overriding
Public Overridable Sub ProcedureName()
Statements
End Sub

Public Overridable Function ProcedureName() As DataType


Statements
End Sub

Copyright © 2014 Pearson Education, Inc. 157


Overriding Sub Procedures and
Functions Syntax for Derived Class
• Derived class must explicitly override
AccessSpecifier Overrides Sub ProcedureName()
Statements
End Sub

AccessSpecifier Overrides Function ProcedureName() _


As DataType
Statements
End Sub

Copyright © 2014 Pearson Education, Inc. 158


Overriding Methods
• The general format of a procedure that overrides a base class procedure is
as follows:
AccessSpecifier Overrides Sub ProcedureName()
Statements
End Sub
• The general format of a function that overrides a base class function is as
follows:
AccessSpecifier Overrides Function FunctionName() As DataType
Statements
End Sub

• When overriding methods and procedures, remember that:


– A derived class cannot access methods or property procedures in the
base class that are declared as Private
– A derived class must keep the same access level as the base class

Copyright © 2014 Pearson Education, Inc. 159


Object Class
• Object class
– Class from which every class is derived
– Ultimate base class
– Contains
• ToString( ) method - returns fully-qualified class
name of object

Copyright © 2014 Pearson Education, Inc. 160


ToString( ) Method
• ToString( ) method
– Can be overridden in derived class, so it
returns string representation of data stored in
derived class object

Copyright © 2014 Pearson Education, Inc. 161


ToString( ) Override Example
• Derived class must override ToString( )
' Overriden ToString method
Public Overrides Function ToString() As String
' Return a string representation of a vehicle
Dim strMsg As String

strMsg = "Passengers: " & Passengers.ToString & _


" MPG: " & MilesPerGallon.ToString

Return strMsg
End Function

Copyright © 2014 Pearson Education, Inc. 162


Overriding the ToString Method
• Every class that you create in Visual Basic is derived
from a built-in class named Object
– The Object class has a method named ToString
– You can override this method so it returns a string representation
of the data stored in an object
' Overridden ToString method
Public Overrides Function ToString() As String
' Return a string representation of a vehicle.
Dim str As String

str = "Passengers: " & intPassengers.ToString() &


" MPG: " & dblMPG.ToString()
Return str
End Function
Copyright © 2014 Pearson Education, Inc. 163
Inheritance Exercise 2
• Create a program with
– Controls
– Student Class (inherits from Person)
• Data member: program of study
• Property procedure for program of study
• ToString( ) method to display Student

Copyright © 2014 Pearson Education, Inc. 164


Constructors
• Constructors
– Both base class and derived class may have
a constructor named New( )
– When derived class object is created
• Base class constructor will be called first
• Then, derived class constructor will be called

Copyright © 2014 Pearson Education, Inc. 165


Base Class and 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

Copyright © 2014 Pearson Education, Inc. 166


Base and Derived Class
Constructors Example
Public Class Vehicle

Public Sub New()


MessageBox.Show("This is the base class constructor.")
End Sub
' (other properties and methods...)
End Class

Public Class Truck


Inherits Vehicle

Public Sub New()


MessageBox.Show("This is the derived class constructor.")
End Sub
' (other properties and methods...)
End Class

Copyright © 2014 Pearson Education, Inc. 167


Inheritance Exercise 3
• Create a program with
– Controls
– Student Class (inherits from Person)
• Data member: program of study
• Property procedure for program of study
• ToString( ) method to display Student
• Add constructor New( )

Copyright © 2014 Pearson Education, Inc. 168


Protected Members
• Protected access specifier
– Allows derived class objects to reference
protected members of base class
– Access to Protected members of base class
• Works like Private in base class
• Works like Public in derived class

Copyright © 2014 Pearson Education, Inc. 169


Protected Members
• The Protected access specifier may be used in
the declaration of a base class member, such as the
following:

– Protected base class members are treated as


• Public to classes derived from this base
• Private to classes not derived from this base

• In Tutorial 12-4, you complete an application that


uses inheritance

Copyright © 2014 Pearson Education, Inc. 170


Topics Covered
• Topics covered
– 12.1 Classes and Objects
– 12.2 Creating a Class
– 12.3 Collections
– 12.4 Focus on Problem Solving: Creating the
Student Collection Application
– 12.5 Object Browser
– 12.6 Introduction to Inheritance

Copyright © 2014 Pearson Education, Inc. 171

You might also like