STARTING OUT WITH Visual Basic 2008 FOURTH EDITION
STARTING OUT WITH Visual Basic 2008 FOURTH EDITION Tony Gaddis Haywood Community College Kip Irvine Florida International University Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 1
Chapter 12 Classes, Exceptions, Collections, and Scrollable Controls Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Introduction n n Classes n Abstract Data Types n Objects, Properties, Methods Exceptions Collections Object Browser Scrollable Controls Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 3
12. 1 Classes and Objects Classes Are Program Structures That Define Abstract Data Types and Are Used to Create Objects Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Abstract Data Types n n 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 n Defines a general type of animal but not a specific breed, color, or size n A dog is like a data type n A specific dog is an instance of the data type Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 5
Classes n n n A class is a program structure that defines an abstract data type n Must create the class first n Then can create instances of the class Class instances share common attributes VB forms and controls are classes n Each control in the toolbox represents a class n Placing a button on a form creates an instance, or object, of the class Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 6
Class Properties, Methods, & Events n n 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 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 7
Object Oriented Design n n The challenge is to design classes that effectively cooperate and communicate Analyze application requirements to determine ADTs that best implement the specifications Classes are fundamental building blocks n Typically represent nouns of some type A well-designed class may outlive the application n Other uses for the class may be found Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 8
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. n n Nouns from the specification above typically become classes in the program design Verbs such as calculate GPA and search become methods of those classes Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 9
OOD Class Characteristics Class Attributes (properties) Operations (methods) Student Last. Name, First. Name, Id. Number Display, Input Student. List All. Students, Count Add, Remove, Find. Student Course Semester, Name, Grade, Credits Display, Input Transcript Course. List, Count Display, Search, Calc. Grade. Avg Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 10
Interface and Implementation n Class interface is the portion of the class visible to the application programmer n Made available by creating properties, methods, and events that are public Class implementation is the portion of the class hidden from client programs n Kept hidden by designating member variables, properties, & methods as private Hiding of data and procedures inside a class is referred to as encapsulation Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 11
12. 2 Creating 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 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Class Declaration Public Class Student Member. Declarations End Class n n n Student is the name of the class Examples of Member. Declarations are presented in the following slides To create a new class: n Click Add New Item button on toolbar n Select Class from Add New Item dialog box n Provide a name for the class and click Add n Adds a new, empty class file (. vb) to project Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 13
Member Variables n n A variable declared inside a class declaration Syntax: Access. Specifer Variable. Name As Data. Type n n Access. Specifier may be Public or Private Example: Public Class Student Public str. Last. Name As String Public str. First. Name As String Public str. Id As String End Class Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley ‘Holds last name ‘Holds first name ‘Holds ID number Slide 12 - 14
Creating an Instance of a Class n n A two step process creates an instance of a class Declare a variable whose type is the class Dim freshman As Student n Create instance of the class with New keyword and assign the instance to the variable freshman = New Student() n n freshman defined here as an object variable Can accomplish both steps in one statement Dim freshman As New Student() Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 15
Accessing Members n Can work with Public member variables of a class object in code using this syntax: object. Variable. member. Variable n For example: n If freshman references a Student class object n And Student class has public member variables str. First. Name, str. Last. Name, and str. ID n Can store values in member variables with freshman. str. First. Name = "Joy" freshman. str. Last. Name = "Robinson" freshman. str. Id = "23 G 794" Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 16
Property Procedure n n n A property procedure is a function that defines a property Controls access to property values Procedure has two sections: Get and Set n Get code executes when value is retrieved n 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 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 17
Property Procedure Syntax Public Property. Name() As Data. Type Get Statements End Get Set(Parameter. Declaration) Statements End Set End Property Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 18
Property Procedure Example Public Class Student ' Member variables Private sng. Test. Avg As Single Public Property Test. Average() As Single Get Return sng. Test. Avg End Get Set(By. Val value As Single) If value >= 0. 0 And value <= 100. 0 Then sng. Test. Avg = value Else Message. Box. Show( _ "Invalid test average. ", "Error") End If End Set End Property End Class Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 19
Setting and Validating a Property n Test. Average property is set as shown: Dim freshman as New Student() freshman. Test. Average = 82. 3 n Passes 82. 3 into value parameter of Set n If in the range 0. 0 to 100. 0, value is stored n If outside the range, message box displayed instead of value being stored Set(By. Val value As Single) If value >= 0. 0 And value <= 100. 0 Then sng. Test. Avg = value Else Message. Box. Show( _ "Invalid test average. ", "Error") End If End Set Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 20
Read-Only Properties n n n Useful at times to make a property read-only Allows access to property values but cannot change these values from outside the class Add Read. Only keyword after access specifier Public Read. Only Property. Name() As Data. Type Get Statements End Get End Property n This causes the property. Name to be read-only -not settable from outside of the class Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 21
Read-Only Property Example ' Test. Grade property procedure Read. Only Property Test. Grade() As Char Get If sng. Test. Average >= 90 return "A“c Else If sng. Test. Average >= 80 return "B“c Else If sng. Test. Average >= 70 return "C“c Else If sng. Test. Average >= 60 return "D“c Else return "F“c End If End Get End Property Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 22
Object Removal & Garbage Collection n 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 freshman = Nothing n n Object is a candidate for garbage collection when it is no longer referenced by any object variable The garbage collector monitors for and automatically destroys objects no longer needed Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 23
Going Out of Scope n n An object variable instantiated within a procedure is local to that procedure An object goes out of scope when n Referenced only by local variables and n 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 n Reference remains when procedure ends Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 24
Going Out of Scope, Example Sub Create. Student() Dim sophomore As Student sophomore = New Student() sophomore. First. Name = "Travis" sophomore. Last. Name = "Barnes" sophomore. Id. Number = "17 H 495" sophomore. Test. Average = 94. 7 g_student. Var = 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_student. Var is a module-level variable. ) Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 25
Comparing Object Variables n Multiple variables can reference the same object Dim college. Student As Student Dim transfer. Student As Student college. Student = New Student() transfer. Student = college. Student n Can test if two variables refer to same object n n Must use the Is operator The = operator cannot be used to test for this If college. Student Is transfer. Student Then ' Perform some action End If Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 26
Is. Not & Nothing Object Comparisons n Use the Is. Not operator to determine that two variables do not reference the same object If college. Student Is. Not transfer. Student Then ' Perform some action End If n Use the special value Nothing to determine if a variable has no object reference If college. Student Is Nothing Then ' Perform some action End If Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 27
Creating an Array of Objects n Can create an entire array of object variables n Declare an array whose type is a class n Instantiate an object for each element ' Declare the array Dim math. Students(9) As Student Dim i As Integer For i = 0 To 9 ' Assign each element to an object math. Students(i) = New Student() Next i Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 28
Objects As Procedure Arguments n Can use object variables as arguments to a procedure or function n Example: student object s as an argument Sub Display. Student. Grade(By. Val s As Student) ' Displays a student’s grade. Message. Box. Show("The grade for " & _ s. First. Name & " " & s. Last. Name & _ " is " & s. Test. Grade. To. String) End Sub n Pass object variable with the procedure call Display. Student. Grade(freshman) Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 29
Objects Passed By. Val and By. Ref n n If argument is declared using By. Ref n Values of object properties may be changed n The original object variable may be assigned to a different object If argument is declared using By. Val n Values of object properties may be changed n The original object variable may not be assigned to a different object Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 30
Functions Can Return Objects n n n Example below instantiates a student object Prompts for and sets its property values Then returns the instantiated object Dim freshman As Student = Get. Student() … Function Get. Student() As Student Dim s As New Student() s. First. Name = Input. Box("Enter first name. ") s. Last. Name = Input. Box("Enter last name. ") s. Id. Number = Input. Box("Enter ID number. ") s. Test. Avg = CSng(Input. Box("Enter test average. ")) Return s End Function Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 31
Class Methods n n In addition to properties, a class may also contain Sub procedures and functions Methods are Sub procedures and functions defined in a class Typically operate on data stored in the class The following slide shows a Clear method for the Student class n Method called with freshman. Clear() n Method clears member data in the Student class object referenced by freshman Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 32
Clear Method for Student Class Public Class Student ' Member variables Private str. Last. Name As String Private str. First. Name As String Private str. Id As String Private sng. Test. Avg As Single (. . . Property procedures omitted. . . ) 'Holds last name first name ID number test avg ' Clear method Public Sub Clear() str. First. Name = String. Empty str. Last. Name = String. Empty str. Id = String. Empty sng. Test. Avg = 0. 0 End Sub End Class Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 33
Constructors n n n 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 n The statement freshman = New Student() n Creates an instance of the Student class n Executes constructor to initialize properties of the Student object referenced by freshman Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 34
Constructor Example Public Class Student ' Member variables Private str. Last. Name As String Private str. First. Name As String Private str. Id As String Private sng. Test. Avg As Single 'Holds last name first name ID number test avg ' Constructor Public Sub New() str. First. Name = "(unknown)" str. Last. Name = "(unknown)" str. Id = "(unknown)" sng. Test. Avg = 0. 0 End Sub (The rest of this class is omitted. ) End Class Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 35
Finalizers n n n VB provides a class method named Finalize Called automatically just before garbage collector removes an instance of a class Select Finalize from method name drop-down list to let Visual Basic create the following template Protected Overrides Sub Finalize() My. Base. Finalize() End Sub n Add your code following My. Base. Finalize() Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 36
Using the Output Window n n n Usually shown at bottom of Visual Studio display If not appearing, click View, Other Windows, then Output to display A valuable debugging tool Messages about an application displayed here Can add your own messages to Output window using Debug. Write. Line method Debug. Write. Line(Output) n n Causes the expression Output to appear in the Output window Insert following code in form Load event to enable Debug. Listeners. Add(New Console. Trace. Listener()) Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 37
Create a Class n Tutorial 12 -1 demonstrates code needed to create the Student class Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 38
12. 3 Collections 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 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Collections n n n 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 shrink as items are added and removed The items stored in a collection do not have to be of the same type Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 40
A Collection is a Class Dim customers As Collection customers = New Collection() ' Or alternatively Dim customers As New Collection() n n New collections are instantiations of the Collection Class The Collection Class provides methods and properties for use with individual collections Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 41
Adding Items to a Collection Object. Add(Item [, Key] [, Before] [, After]) n n n Add is a method of the Collection class Object is a variable that refers to a collection Item can be an object, variable, or value that is added to the collection Key is a unique value optionally used to identify a member of the collection Before or After optionally specifies where a new item should be placed in the collection Default is to insert at the end of the collection Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 42
Uses of Before and After n Add cust. Data with key "Smith" before the item with key "Thomas“ customers. Add(cust. Data, "Smith", "Thomas") n Add cust. Data with key "Smith" after the item with key "Reece“ customers. Add(cust. Data, "Smith", , "Reece") n Add cust. Data after 3 rd item in collection customers. Add(cust. Data, , , 3) Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 43
Add Method Exceptions n An exception can occur when adding to a collection so Try-Catch should be used n Cannot add member with same key as another member of the collection n If a key or index is specified for a Before or After, the value must exist Try customers. Add(cust. Data, "Smith") Catch ex as Argument. Exception Message. Box. Show(ex. Message) End Try Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 44
Accessing Item by Their Indices n n Can access an item in a collection using an index value Index value can be used in two ways: n Using the collection’s Item method Object. Item(Index) n Item is the default method so it can be omitted Object(Index) n Get value at index 3 of names collection by: names. Item(3) –or- names(3) Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 45
Index. Out. Of. Range Exception n If an invalid index is encountered, an index out of range exception will occur Should use Try-Catch to trap such messages Ctype casts collection object to Customer object Try Dim cust as Customer ‘Get collection index from user input Dim index as Integer = CInt(txt. Index. Text) ‘Locate the customer in the collection cust = CType(customers. Item(index), Customer) Catch ex as Index. Out. Of. Range. Exception Message. Box. Show(ex. Message) End Try Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 46
The Count Property n n n The Count property of a collection gives the number of current items in the collection Note that, unlike an array, a collection index is not zero based n First item in a collection found at index 1 Following code adds collection items to a list box Dim int. X As Integer For int. X = 1 To names. Count lst. Names. Items. Add(names(int. X). To. String()) Next int. X Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 47
Searching for an Item by Key Value n Item method can be used to retrieve an item with a specific index Object. Item(Expression) n n n If Expression is a string, it is used as a key to search for a member with a matching key 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 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 48
Retrieving Item Examples n Find student. Collection item with key 49812 n If Option Strict on, must cast result to Student Dim s as Student s = CType(student. Collection. Item(“ 49812”), Student) n Retrieve all members by index and display Last. Name property in a message box Dim int. Index as Integer Dim s as Student For int. Index = 1 to student. Collection. Count s = Ctype(student. Collection. Item(int. Index), Student) Message. Box. Show(s. Last. Name) Next int. Index Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 49
Using References Versus Copies n When an Item in a collection is a fundamental VB data type, only a copy is retrieved n This code does not change the item at index 1 Dim int. Num as Integer int. Num = CType(numbers(1), Integer) int. Num = 0 n The Item in this collection is an object so: n A reference is returned instead of a copy n Last. Name of object in collection is changed Dim s as Student s = CType(student. Collection. Item("49812"), Student) s. Last. Name = "Griffin" Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 50
For Each Loop with a Collection n Can use a For Each loop to read members of a collection n Eliminates the counter variable required to use a For…Next n Also no need to compare to Count property Dim s As Student For Each s In student. Collection Message. Box. Show(s. Last. Name) Next s Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 51
Removing Members of a Collection Object. Remove(Expression) n n n Remove is a method of the Collection class Object refers to collection Member removed from Expression can be n Numeric and interpreted as an index n Or a string and interpreted as a key value n Exception thrown if Expression not found Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 52
Removing Member Examples n Verify “ 49812” is a key value in collection, then remove member with this key value If student. Collection. Contains(“ 49812”) Then student. Collection. Remove("49812") End If n Verify index location 7 exists in collection, then remove member at this index location Dim int. Index As Integer = 7 If int. Index > 0 and _ int. Index <= student. Collection. Count Then student. Collection. Remove(int. Index) End If Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 53
Working with Collections n n Since a collection is an instance of a class n Procedures accept collections as arguments n Functions can return a collection n Follow same guidelines as any class object Parallel collections work like parallel arrays n Can use index to relate parallel collections just as we did with arrays n Or can use key values to relate collections Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 54
12. 4 The Student Collection Application Create an Application that Uses a Collection of Student Objects Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Student Collection Application Forms § Select student ID number from list box to see detail information for the student § Click Remove Student button remove an instance of the Student class § Click Add Student button to create a new instance of the Student class § Add Student form Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 56
12. 5 The Object Browser Is a Dialog Box That Allows You to Browse All Classes and Components Available to Your Project Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Using the Object Browser n n n A dialog box with information about objects used in a project Allows you to examine n Information about forms used in a project n Classes created for the project n Other components used by VB in the project Tutorial 12 -3 uses the Object Browser to examine the Student Collection project Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 58
Object Browser, Example Student class selected Class members shown Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 59
12. 6 Scroll Bars and Track Bars The HScroll. Bar, VScroll. Bar, and Track. Bar Controls Provide a Graphical Way to Adjust a Number Within a Range of Values Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Visual Appearance and Usage n n n HScroll. Bar and VScroll. Bar look like normal scroll bars Track. Bar has an arrow pointer as the slider with tick marks Scrollable controls hold integers in their Value property n Position of slider corresponds to Value n Move scroll bar to increase or decrease Value n Right increases, left decreases horizontal bar n Up increases, down decreases vertical bar Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 61
Scrollable Control Properties n n n Minimum – the bar’s lowest possible value Maximum – the bar's highest possible value Value – the bar's value at the current position Large. Change – change in the Value property with a mouse click on/near the slider Small. Change – change in the Value property for a mouse click on an arrow at the end Tick. Frequency - for Track. Bar only, the number of units between tick marks n With min=0 and max=1000, if Tick Frequency is 100, 10 tick marks are shown on the bar Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 62
Coding for Scrollable Controls n n n Any change to the position of a scroll bar generates a Scroll event n Allows program to react to a shift in scroll bar Standard prefixes for these controls n Horizontal scroll bar is hsb n Vertical scroll bar is vsb n Track. Bar is tb Tutorial 12 -4 demonstrates how to set up Scroll events and use of these controls Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 63
12. 7 Introduction 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 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Why Inheritance? n n Inheritance allows new classes to derive their characteristics from existing classes The Student class may have several types of students such as n Graduate. Student n Exchange. Student n Student. Employee 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 © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 65
Base and Derived Classes n n n The Base Class is a general-purpose 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 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 66
The Vehicle Class (Base Class) n n n Consider a Vehicle class with the following: n Private variable for number of passengers n Private variable for miles per gallon n Public property for number of passengers (Passengers) n Public property for miles per gallon (Miles. Per. Gallon) This class holds general data about a vehicle Can create more specialized classes from the Vehicle class Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 67
The Truck Class (Derived Class) n n n Declared as: Public Class Truck Inherits Vehicle ' Other new properties ' Additional methods End Class Truck class derived from Vehicle class n Inherits all non-private methods, properties, and variables of Vehicle class Truck class defines two properties of its own n Max. Cargo. Weight – holds top cargo weight n Four. Wheel. Drive – indicates if truck is 4 WD Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 68
Instantiating the Truck Class n n n Instantiated as: Dim pick. Up as New Truck() pick. Up. Passengers = 2 pick. Up. Miles. Per. Gallon = 18 pick. Up. Max. Cargo. Weight = 2000 Pickup. Four. Wheel. Drive = True Values stored in Max. Cargo. Weight and Four. Wheel. Drive properties n Properties declared explicitly by Truck class Values also stored in Miles. Per. Gallon and Passengers properties n Properties inherited from Vehicle class Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 69
Overriding Properties and Methods n n Sometimes a base class property procedure or method must work differently for a derived class n Can override base class method or property n 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 n VB uses overridden version in derived class n Version in base class is not used Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 70
Property Override Example n n n 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: n Coding Passengers property in derived class n Specify Overridable in base class property n Specify Overrides in derived class property Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 71
Overridable Base Class Property n Overridable keyword added to base class property procedure Public Overridable Property Passengers() As Integer Get Return int. Passengers End Get Set(By. Val value As Integer) int. Passengers = value End Set End Property Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 72
Overridden Derived Class Property n Overrides keyword and new logic added to derived class property procedure Public Overrides Property Passengers() As Integer Get Return My. Base. Passengers End Get Set(By. Val value As Integer) If value >= 1 And value <= 2 Then My. Base. Passengers = value Else Message. Box. Show("Passengers must be 1 or 2", _ "Error") End If End Set End Property Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 73
Overriding Methods n n n Overriding a method is similar to a property Specify Overridable and Overrides keywords An overridable base class method Public Overridable Sub Procedure. Name() Public Overridable Function Procedure. Name() As Data. Type n An overriding derived class method Public Overrides Sub Procedure. Name() Public Overrides Function Procedure. Name() As Data. Type Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 74
Overriding the To. String Method n n n Every programmer created class is derived from a built-in class named Object class has a method named To. String which returns a fully-qualified class name Method can be overridden to return a string representation of data stored in an object Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 75
To. String Override Example n n Object class To. String method is Overridable Vehicle class might override the To. String method as shown below ' Overriden To. String method Public Overrides Function To. String() As String ' Return a string representation ' of a vehicle. Dim str As String str = "Passengers: " & int. Passengers. To. String & _ " MPG: " & sng. MPG. To. String Return str End Function Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 76
Base & Derived Class Constructors n n 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 n The constructor of the base class will be called first n Then the constructor of the derived class will be called Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 77
Protected Members n n In addition to Private and Public, the access specifier may be Protected n Protected base class members are treated as public to classes derived from this base n 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 Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 12 - 78
- Slides: 78