1 / 76

Chapter 12

Chapter 12. Classes, Exceptions, Collections, and Scrollable Controls. Chapter 12 Introduction. Chapter 12 Topics. Classes Abstract Data Types Objects, Properties, Methods Exceptions Collections Object Browser Scrollable Controls. Section 12.1 Classes and Objects.

hieu
Télécharger la présentation

Chapter 12

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls

  2. Chapter 12Introduction

  3. Chapter 12 Topics • Classes • Abstract Data Types • Objects, Properties, Methods • Exceptions • Collections • Object Browser • Scrollable Controls

  4. Section 12.1Classes and Objects Classes Are Program Structures That Define Abstract Data Types and Are Used to Create Objects

  5. 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 abstractionis 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

  6. Classes • A classis 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

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

  8. 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

  9. Object Oriented Design Example • Nouns from the specification above usually become classes in the program design • Verbs such as calculate GPA and search become methods of those classes 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.

  10. OOD Class Characteristics ClassAttributes (properties)Operations (methods) Student LastName, FirstName, Display, Input IdNumber StudentList AllStudents, Count Add, Remove, FindStudent Course Semester, Name, Display, Input Grade,Credits Transcript CourseList, Count Display, Search, CalcGradeAvg

  11. Interface and Implementation • Class interfaceis the portion of the class visible to the application programmer • Class implementationis 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

  12. 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

  13. 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 ClassName MemberDeclarations End Class

  14. Member Variables • A variable declared inside a class declaration • Syntax: • AccessSpecifier may be Public or Private • Example: AccessSpecifer VariableName As DataType Public Class Student Public strLastName As String ‘Student last name Public strFirstName As String ‘Student first name Public strId As String ‘Student ID number End Class

  15. 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 Student freshman = New Student() Dim freshman As New Student()

  16. 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 object.memberVariable freshman.strFirstName = "Joy" freshman.strLastName = "Robinson" freshman.strId = "23G794"

  17. 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

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

  19. Property Procedure Example Public Class Student ' Member variables Private sngTestAvg As Single Public Property TestAverage() As Single Get Return sngTestAvg End Get Set(ByVal value As Single) If value >= 0.0 And value <= 100.0 Then sngTestAvg = value Else MessageBox.Show( _ "Invalid test average.", "Error") End If End Set End Property End Class

  20. 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 stored Dim freshman as New Student() freshman.TestAverage = 82.3 Set(ByVal value As Single) If value >= 0.0 And value <= 100.0 Then sngTestAvg = value Else MessageBox.Show( _ "Invalid test average.", "Error") End If End Set

  21. 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 DataType Get Statements End Get End Property

  22. Read-Only Property Example • ' TestGrade property procedure • ReadOnly Property TestGrade() As Char • Get • If 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 Get • End Property

  23. 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

  24. 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

  25. Going Out of Scope, Example Sub CreateStudent() Dim sophomore As Student sophomore = New Student() sophomore.FirstName = "Travis" sophomore.LastName = "Barnes" sophomore.IdNumber = "17H495" sophomore.TestAverage = 94.7 g_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.)

  26. 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 Student Dim transferStudent As Student collegeStudent = New Student() transferStudent = collegeStudent If collegeStudent Is transferStudent Then ' Perform some action End If

  27. 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

  28. Creating an Array of Objects • Can create an entire array of object variables • Declare an array whose type is a class • Instantiate an object for each element ' Declare the array Dim mathStudents(9) As Student Dim i As Integer For i = 0 To 9 ' Assign each element to an object mathStudents(i) = New Student() Next i

  29. Objects As Procedure Arguments • 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 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)

  30. 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

  31. Functions Can Return Objects • Example below instantiates a student object • Prompts for and sets its property values • Then returns the instantiated object 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

  32. 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

  33. Clear Method for Student Class Public Class Student ' Member variables Private strLastName As String 'Holds last name Private strFirstName As String 'Holds first name Private strId As String 'Holds ID number Private sngTestAverage As Single 'Holds test avg (...Property procedures omitted...) ' Clear method Public Sub Clear() strFirstName = String.Empty strLastName = String.Empty strId = String.Empty sngTestAverage = 0.0 End Sub End Class

  34. Constructors • A constructoris 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

  35. Constructor Example Public Class Student ' Member variables Private strLastName As String 'Holds last name Private strFirstName As String 'Holds first name Private strId As String 'Holds ID number Private sngTestAverage As Single 'Holds test avg ' Constructor Public Sub New() strFirstName = "(unknown)" strLastName = "(unknown)" strId = "(unknown)" testAvg = 0.0 End Sub (The rest of this class is omitted.) End Class

  36. Create a Class • Tutorial 12-1 demonstrates code needed to set up for the Student class

  37. 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

  38. Collections • A collectionis 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

  39. 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 Collection • customers = New Collection() • ' Or alternatively • Dim customers As New Collection()

  40. 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])

  41. 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)

  42. 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 Try customers.Add(custData, "Smith") Catch ex as ArgumentException MessageBox.Show(ex.Message) End Try

  43. 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.Item(Index) Object(Index)

  44. 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 Customer Try custData = Ctype(customers.Item(5), Customer) Catch ex as IndexOutOfRangeException MessageBox.Show(ex.Message) End Try

  45. The Count Property • The Count property of a collection gives the number of current items in the collection Dim intX As Integer For intX = 1 To names.Count lstNames.Items.Add(names(intX).ToString()) Next intX

  46. 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)

  47. 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)

  48. 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 Student s = Ctype(studentCollection.Item(“49812”), Student) Dim i as Integer Dim s as Student For I = 1 to studentCollection.Count s = Ctype(studentCollection.Item(i), Student) MessageBox.Show(s.LastName) Next i

  49. 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 changed Dim n as Integer n = CType(numbers(1), Integer) n = 0 Dim s as Student s = CType(studentCollection.Item("49812"), Student) s.LastName = "Griffin"

  50. For Each Loop with a Collection • 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 Dim s As Student For Each s In studentCollection MessageBox.Show(s.LastName) Next s

More Related