Академический Документы
Профессиональный Документы
Культура Документы
Chapter 12
Classes, Collections, and Inheritance
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.
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
12.1
Object-Oriented Programming
Object-oriented programming (OOP)
Designing and coding applications with interchangeable software First languages appeared in 1980s
SmallTalk, C++, ALGOL
Examples of objects
Form, button, check box, list box
Lassie is an instance
Classes
Class
Program structure defining abstract data type Steps
Design class first Then design a class client that creates an instance of class
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)
10
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
12
13
14
15
16
17
18
Implementation
Portion of class hidden from client programs
Private member variables, properties, and methods
Encapsulation
Hiding data and methods inside a class
20
Client Program
Client program
Uses class to
Instantiate an object Access data members Call methods
21
12.2
Creating a Class
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
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
25
Adding a Class
26
27
Person Class
28
Member Declarations
Member declarations
Variables Constants Methods
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 variables data type
Copyright 2014 Pearson Education, Inc.
30
Note: Initially data members are Public, change to Private after Property procedures are added
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
32
33
Class Instance
To create instance of class in client
Declare reference and create instance
Dim freshman As New Student()
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"
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
36
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
38
39
40
41
Insert Snippet
42
43
44
45
46
47
48
49
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
Step 2
Submit: Declare reference, create instance, populate members from text boxes using property procedures
Data members: first name, last name, age (make Private) Public property procedures for data members
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
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
53
Sample Person.vb
54
Sample Client
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
56
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)
59
60
Storing Objects
Object storage
When instantiated
Memory space is allocated
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
62
63
64
sophomore.FirstName = "Travis" sophomore.LastName = "Barnes" 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
66
Is Operator
Is operator
Determines if two variables reference same object
If collegeStudent Is transferStudent Then ' Perform some action End If
67
IsNot Operator
IsNot operator
Determines if two variables do not reference same object
If collegeStudent IsNot transferStudent Then ' Perform some action End If
68
Nothing
Nothing keyword
Identifies no object reference
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
70
71
Example
Dim index As Integer For index = 0 To mathStudents.Length - 1 ' Set each element to Nothing mathStudents(index) = Nothing Next index
72
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
74
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
76
ToString( ) Method
ToString( ) method
Inherited from Object class Class overrides method to return a string representation of data stored in class
77
78
Clear( ) Method
Clear( ) method
Class may define a clear method to reset data stored in class
79
Constructors
Constructor
New() method
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
83
84
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.
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
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
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
'''
90
91
Output Window
Output window
Valuable debugging tool Display by
Clicking View/Other Windows/ Output Pressing Ctrl + Alt + O key combination
92
93
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
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
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
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
100
' add value into collection customers.Add(myCustomer) ' add value with key to collection customers.Add(myCustomer, myCustomer.Name)
101
Example
Try customers.Add(myCustomer, myCustomer.Name) Catch ex As ArgumentException MessageBox.Show(ex.Message, "Error Adding") End Try
102
Collection Exercise 1
Modify program with
Controls Events
Form Load: Create a collection of people Add: add person to collection
103
104
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
107
108
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
110
111
112
113
114
A class object
A reference to the object is returned Its value can be changed
115
116
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
118
Removing Members
Use Remove( ) method
To remove a member from a collection
Exception thrown if member not found
ArgumentException IndexOutOfRangeException
119
where
CollectionName is name of a collection Expression is string or numeric
Numeric, used as index String, used as key
120
121
122
123
Parallel Collections
Parallel collections
Work like parallel arrays To relate collections, can use
Index Key values
124
' Store hours using key ' Store rate, same key
' same key used to retrieve related data grossPay = hoursWorked.Item(key) * payRate.Item(key)
125
12.4
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
128
12.5
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
130
131
132
12.6
Introduction to Inheritance
133
Inheritance
Inheritance
Allows new class to be based on existing class New class inherits accessible
Member variables Methods Properties
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
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
Derived class
Based on base class Inherits characteristics from base class Note: Base class is parent, and derived class is child
138
139
140
Properties (Public)
Property for Passengers Property for MilesPerGallon
141
142
Properties
MaxCargoWeight holds top cargo weight FourWheelDrive indicates if truck is 4WD
Copyright 2014 Pearson Education, Inc.
143
144
Instantiating a Truck
Instantiated as:
Dim pickUp As New Truck() pickUp.Passengers = 2 pickUp.MilesPerGallon = 18 pickUp.MaxCargoWeight = 2000 Pickup.FourWheelDrive = True
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
146
147
148
149
150
151
152
153
154
155
156
157
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
160
ToString( ) Method
ToString( ) method
Can be overridden in derived class, so it returns string representation of data stored in derived class object
161
162
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
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
165
166
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( )
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
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