1 / 29

Visual Basic Programming II Lecture 9

Visual Basic Programming II Lecture 9. MIS233 Instructor – Larry Langellier. This Week – Classes. Introduction to Object-Oriented Design Understand Classes and Objects Defining Classes with Properties and Methods The Initialize() Event The Terminate() Event Object Variables

erwin
Download Presentation

Visual Basic Programming II Lecture 9

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. Visual Basic Programming IILecture 9 MIS233 Instructor – Larry Langellier

  2. This Week – Classes • Introduction to Object-Oriented Design • Understand Classes and Objects • Defining Classes with Properties and Methods • The Initialize() Event • The Terminate() Event • Object Variables • The Class Browser • Collections Revisited • Good Object-Oriented Programming Practices

  3. What Are Classes and Objects • A Class defines a new data type, similar to a User-Defined Type • Noun • A Class defines a person, place, or thing • A Class is comprised of: • Properties – data variables used to describe members of the Class • Methods – subroutines and functions specific to a Class • Events – messages that instances of a Class will respond to • An Object is an “instance” of a class • The Analogies • The cookie cutter and a batch of cookies • A blueprint used to create numerous houses

  4. Why Use Classes and Objects? • Encapsulation – Hide information and code internally within an object so outside agents can’t change them • Inheritance – Provide common behaviors and attributes among similar classes of objects, but specialize Classes to model their unique aspects • Improved Productivity – Reuse classes which have been built in the past (Forms, etc.) • Increase Quality – “Black-box” solutions can be tested individually and combined to form different applications • Elevate Maintainability – Changes are localized • Real-World Modeling – Think like a person, not a computer

  5. Creating a Class • Creating a Class is similar to adding a Form Module or a Standard (.bas) Code Module • How to Create: • Project Menu -> Add Class Module • Right-mouse click in Project Explorer -> Insert -> Class Module • You may create a new class or load one that was created earlier from disk • Immediately name the Class via the Name property • Example • Create a Class called Product

  6. Object Variables • Object variables are declared similarly to regular variables – using Dim, Static or Public keywords • Example: Dim objProduct As Product • Object variables are references to an object, not the object itself • The value contained in the variable is a 4 byte pointer to another location in memory where the actual object is stored • This means the declaration above gives you a memory location to store the address of an object, but not an actual object • So how do we get an Object???

  7. Creating Instances and Assigning to Object Variables • The New Keyword • Used to create an instance of a class (an object) • Example: New Product • The Set Keyword • Used to assign an object instance to an object variable • Example: Set objProduct = New Product • Combining Variable Declaration and Object Creation • Can be used in an assignment or a variable declaration • Example: Dim objProduct As New Product • The Nothing Keyword • Allows an object variable to be dereferenced (i.e., the variable no longer points to an object) • Example: Set objProduct = Nothing • To test for Nothing use the Is keyword • Example: If objProduct Is Nothing Then…

  8. Class Properties • Adjective • Properties describe an Object • Properties hold data that describe an object and serves to make one Object of a Class unique from another Object of the same Class • Some properties can be read-only, meaning you can see the value but you can’t change it • Some properties can be private and are not accessible at all outside the Object • Properties are also known as Instance Variables, Data Members or Attributes

  9. Adding Properties to a Class • Create Private Data Members (variables) in the General Declaration section of the Class Module • Define Accessor (Get) and Mutator (Set, Let) methods for each property – these can be Public or Private • The Get method enables retrieval of attribute (property) values from an object • Syntax/Example Public Property Get ProductName() As String ProductName = mstrProductName End Property • The Let (non-object) and Set (object) methods allow an object’s attribute value to be changed • Syntax/Example Public Property Let ProductName(sNewVal As String) mstrProductName = sNewVal End Property • Example: 20.4 – Creating and Using OrderItem Class

  10. Utilizing Properties • Now your object has some properties – how do you change them and access them? • Using the Get and Let/Set methods of course! • You’ve been using properties on Forms and Controls for over a semester now • Utilizing them with objects that you’ve created is done the same way – using the “dot” operator • Examples objProduct.ProductName = "A Whatchamacallit" Let objProduct.ProductName = "A Whatchamacallit“ Print objProduct.ProductName

  11. Do It Together! Let’s start to migrate the Mini-Project to an Object-Oriented solution. Create a class called Player that has four properties – Name, Hits, Walks (BB), and At Bats. To implement these properties you will need a private module-level variable for each along with Get and Let property methods for each. Don’t worry about providing much of an interface – simply provide a button that (when clicked) creates 3 player objects (with names and statistics), stores each in an array, then iterates through the array and prints a list of player info to the Form.

  12. Interface Sample

  13. Sample Solution In Player.cls Option Explicit 'local variable(s) to hold property value(s) Private mvarPlayerName As String Private mvarAtBats As Integer Private mvarWalks As Integer Private mvarHits As Integer Public Property Let Hits(ByVal vData As Integer) mvarHits = vData End Property Public Property Get Hits() As Integer Hits = mvarHits End Property Public Property Let Walks(ByVal vData As Integer) mvarWalks = vData End Property Public Property Get Walks() As Integer Walks = mvarWalks End Property

  14. Sample Solution (cont.) Player.cls continued Public Property Let AtBats(ByVal vData As Integer) mvarAtBats = vData End Property Public Property Get AtBats() As Integer AtBats = mvarAtBats End Property Public Property Let PlayerName(ByVal vData As String) mvarPlayerName = vData End Property Public Property Get PlayerName() As String PlayerName = mvarPlayerName End Property

  15. Sample Solution (cont.) In the Form Private Sub cmdTest_Click() Dim Player(3) As Player Dim i As Integer Set Player(1) = New Player Player(1).PlayerName = "Carlos Lee" Player(1).Hits = 130 Player(1).AtBats = 430 Player(1).Walks = 80 Set Player(2) = New Player Player(2).PlayerName = "Paul Konerko" Player(2).Hits = 140 Player(2).AtBats = 450 Player(2).Walks = 75 Set Player(3) = New Player Player(3).PlayerName = "Ray Durham" Player(3).Hits = 180 Player(3).AtBats = 620 Player(3).Walks = 63 Cls For i = 1 To 3 Print Player(i).PlayerName, Player(i).Hits, Player(i).Walks, Player(i).AtBats Next i End Sub

  16. Class Methods • Verb • Methods take action • Methods (subroutines and functions) can be placed inside classes to operate on the class’ properties (data) • Creating a method is no different than writing any other procedure – except that it’s contained in a class module • Methods can be private to the object (not visible outside it) or part of an object’s public interface – simply use the Public or Private keywords • Methods are similar to normal functions and subroutines except that they can only be accessed via an instance (object) of that class – just like Form and Control methods Example: Print objProduct.computeDiscount • Methods are also known as Member Functions, Instance Methods, or Behaviors

  17. Do It Together! Let’s continue enhancing the Player class. Add two methods • BattingAvg • OnBasePct These two methods should use the property values of the Player to compute and return a value BattingAvg = Hits / At Bats OnBasePct = (Hits + Walks) / (At Bats + Walks) Modify the button click event handler to print the player’s batting average and on-base percentage, instead of or in addition to the other statistics

  18. Sample Interface

  19. Sample Solution In Player.cls Public Function battingAvg() As Double battingAvg = Hits / AtBats End Function Public Function onBasePct() As Double onBasePct = (Hits = Walks) / (AtBats + Walks) End Function In the Form 'Declare fixed width strings to hold values, and then… For i = 1 To 3 With Player(i) LSet strName = .PlayerName RSet strHits = .Hits RSet strAtBats = .AtBats RSet strWalks = .Walks RSet strOBP = Format(Round(.onBasePct, 3), "0.000") RSet strBA = Format(Round(.battingAvg, 3), "0.000") End With Print strName; strHits; strAtBats; strWalks; strOBP; strBA Next i

  20. Events • We’ve seen events on Forms and Controls – like the Load event for a Form or the Click event for a CommandButton • Objects can respond to Events also • Initialize Event • Fires each time a new instance of an object is created • Data members (properties) can be initialized and assigned default values • Terminate Event • Used to execute cleanup code • Fires when the last reference to an object is removed • Generally involves Memory Management (e.g. setting object variables to Nothing or ReDim arrays to reclaim memory) • Example: 20.5 – Demonstrating the Terminate() Event

  21. Collections • Visual Basic provides a built-in Class called Collection • A Collection allows you to: • Add objects to it • Access individual items within it • Iterate across all instances that it contains • Remove any object from it • Ask how many objects are in it • Collections are classes and as such must be declared and assigned to a variable the same way all objects are: Dim Students As Collection Set Students = New Collection • Collections are indexed starting at 1 (not 0)

  22. Collection Methods • Add – Add an item to a Collection aCollection.Additem, key, before, after • Remove – Remove an item from a Collection aCollection.Removeindex • Item – Returns an item from a collection by • it’s index (numeric position); or • key (string identifier assigned when it was added) aCollection.Item(index) • An index can be: • An integer from 1 to the collection’s Count property • A string matching the key when the object was added • Count – How many objects are in the collection aCollection.Count

  23. For Each…Next • A new type of For loop is available for Collections – it allows you to easily iterate through the Collection’s elements • Syntax: For EachanItemInaCollection <statements> Next • Examples (both do the same thing): For Each Student In Students For i = 1 To Students.Count Student Students.Item( i ) Next Student Next i • Example: 20.6 – Using a Collection Object

  24. Do It Together! Create a Team class • Contains 1 Property • Players – a collection of Player objects • Has 1 Method • PrintTeamStats – produces a printout similar to the prior JDI • Implement behavior for the Initialize() and Terminate() events • Create and Destroy the collection of three sample players The button click event-handler will simply create a Team object and call the PrintTeamStats method

  25. Sample Solution In Team.cls Full solution in PlayerProps.vbp Private mcolPlayers As Collection PrivateProperty Set Players(ByRef vData As Collection) Set mcolPlayers = vData End Property Private Property Get Players() As Collection Set Players = mcolPlayers End Property

  26. Sample Solution (cont.) Team.cls continued Private Sub Class_Initialize() Dim objPlayer As Player Set Players = New Collection Set objPlayer = New Player With objPlayer .PlayerName = "Carlos Lee" .Hits = 130 .AtBats = 430 .Walks = 80 End With Players.Add objPlayer, objPlayer.PlayerName 'Repeat for the other two players End Sub Private Sub Class_Terminate() Set Players = Nothing End Sub

  27. Sample Solution (cont.) Team.cls continued Public Sub PrintTeamStats() Dim objPlayer As Object Dim strName As String * 15 Dim strHits As String * 4 Dim strAtBats As String * 4 Dim strWalks As String * 4 Dim strOBP As String * 6 Dim strBA As String * 6 frmPlayers.Cls For Each objPlayer In Players With objPlayer LSet strName = .PlayerName RSet strHits = .Hits RSet strAtBats = .AtBats RSet strWalks = .Walks RSet strOBP = Format(Round(.onBasePct, 3), "0.000") RSet strBA = Format(Round(.battingAvg, 3), "0.000") End With frmPlayers.Print strName; strHits; strAtBats; strWalks; strOBP; strBA Next objPlayer End Sub

  28. Details… • Next Class • Read Chapter 23: Accessing and Manipulating Databases with VB • Homework #10 will be due at the beginning of class

  29. Semester Project –Preliminary Design • This Design should be comprised of three elements: • A Prototype of your User-Interface – similar in spirit to exercise 21.2 (page 499) that we looked at in detail last week • An Object Model definition • What Classes are you going to have? • What Properties will each class have? • What Behaviors (Methods) will each class have? • A Database schema • What Tables will your database contain? • What Fields will each table have? • What will the Primary Keys be for each table? • What Foreign Keys will you have between tables?

More Related