apii 3 oopb

16
4/22/2016 1 O bj ectO ri ent ed P rogramm i ngI I Usi ng Vi sual St udio Objectives  T o :  C om pare c las s es to s tandard m odules  Createan obje c t in terfac e E xpos e objec t attrib u tesas properties E xpose f un ctionsas m ethods  Ins tantiate objec ts from c las ses  Bin d an obje c t refere n c e to a variable  R elease object ref erenc es  U nders tand objec t lifetimes OOP 2 OOP and Cl asse s  Object-oriented programming is an advanced m eth odology th at en abl es you to c reate more robus t applic ati ons.  P rogr am m ing c las s es is the f oun dat ion of OOP .  C las s es are th e tem plates us ed to ins tantiat e objects. OOP 3 Cl assesvs Stand ardM odu l es OOP 4

Upload: mogeni-jnr

Post on 13-Apr-2018

222 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: APII 3 OOPb

7/25/2019 APII 3 OOPb

http://slidepdf.com/reader/full/apii-3-oopb 1/16

4/22/20

Object Oriented Programming II

Using Visual Studio

Objectives

 To :

 Compare classesto standard modules

 Createan object interface

Expose object attributesasproperties

Expose functionsas methods

 Instantiate objectsfrom classes

 Bind an object reference to a variable

 Releaseobject references

 Understandobject lifetimesOOP

2

OOP and Classes

 Object-oriented programming is an advancedmethodology that enables you to create morerobust applications.

 Programming classesis the foundation of OOP.

 Classes are the templates used to instantiateobjects.

OOP

3

Classes vsStandard Modules

OOP

4

Page 2: APII 3 OOPb

7/25/2019 APII 3 OOPb

http://slidepdf.com/reader/full/apii-3-oopb 2/16

4/22/20

Classes vsStandard Modules

Similarities:

How they appear in the Visual Studiodesign environment

Howyouwrite code within them.

Differences

Their behaviour at runtime (see next slide)

OOP

5

Standard Modules vsClasses6

Standard Modules Classes

How Their Data Behaves

All module-level d ata (static and module-

level variables) is shared by all procedures

withinthe module.

There are never multiple instances of the

moduledata.

Objectsare instantiatedfroma class.

Eachobjectreceivesits ownset of moduledata.

Module-level variables exist for the lifetime

ofthe application.

Module variables exist only for the duration of an object’s

lifetime. Objects can be created and destroyed as n eeded,

and when an object is destroyed, all its data is destroyed as

well.

How Their Functions and Procedures Behave

When you define a standard module, its

public functions and procedures are

instantly available to other modules w ithin

yourapplication.

Public functions and procedures of classes are NOT

immediatelyavailableto yourprogram.

An object would have to be instantiated before thepublicvariablesand routineswould be available.Classes are templates for objects. At runtime, your code

doesn’t interact with the code in the class module per se, but 

it instantiates objects derivedfrom the class.

Each object acts as its own class “module” and thus has itsownset of module data.

Client vsServer Code

 Usually classes are exposed externally to otherapplications

Theserver

 theapplication that hasthe class’scode

Theclient

 an application that createsand usesinstancesof a class.

 When an application that has the classes also usesinstancesof those classes, the application itself actsasbothaclientandaserver.

Clientcode

 Thecode instantiating an object derived f roma class.

7

Class Programming Example8

OOP

Page 3: APII 3 OOPb

7/25/2019 APII 3 OOPb

http://slidepdf.com/reader/full/apii-3-oopb 3/16

4/22/20

Class Programming Example

  Create a new Windows Application calledClassProgramming Example 

  Rename    the default formClassExampleForm.vb , and set its   Text 

property toClassProgramming Example.

  Add a new class to the project by choosingProject,AddClassfromthemenu bar and

  Save the classwith the name  clsMyClass.vb 

OOP

9

Creating an Object Interface

Class Programming Example10

OOP

Class Programming ExampleCreating an Object Interface

  For an object to be created from a class, the class mustexposean interface.

  an interface being a set of exposed functionality (properties,methods,and events).

  An interface is the means by which client code communicateswiththe object derived f romthe class.

  A class interface consists of one or more of the followingmembers:

  Properties

  Methods   Events

OOP

11

Class Programming ExampleCreating an Object Interface

  Any and all communication between the client and the objectmust occur through this interface:

  Some classes expose a limited interface, and others exposecomplex interfaces.

  Thecontent and quantity of your class’s interface are up to you.OOP

12

Page 4: APII 3 OOPb

7/25/2019 APII 3 OOPb

http://slidepdf.com/reader/full/apii-3-oopb 4/16

4/22/20

Class Programming ExampleCreating an Object Interface

 For example, assume that you’re creating anEmployee class.

 You must first decide how you want client code tointeract withit.

 You’ll want to consider both the data containedwithin the object and the functions that the objectcan perform.

Properties and methods are the most commonlyused interfacemembers.

OOP

13

Class Programming ExampleCreating an Object Interface

Properties

 You might want client code to be able to retrieve anemployee’sinformatione.g. name, sex, age, and the date of hire.

 For client code to get these values from the object, theobject must expose an interface member for each of theseitems.

Remember, thevaluesexposed by an object are calledproperties.

 Therefore, eachpieceof data would have to be exposed asa propertyof the Employee object.

OOP

14

Class Programming ExampleCreating an Object Interface

Methods

 In addition to properties, you canexpose simple or complexfunctions, such asDeleteor AddNew.

 E.g. theEmployee object’sDelete  functionmight be complex.

  It would need to perform all the actions necessary to delete anemployee,e.g.:

 removing theemployee froman assigned department,

 notifying the accounting department to remove the employeefromthepayroll,

 notify ing the security department to revoke the employee’ssecurity access.

 Remember publicly exposed functions of an object arecalled methods.

OOP

15

Class Programming ExampleCreating an Object Interface

Events

For even more interaction between the client andtheobject, youcanexpose customevents.

Customobject events are similar to the eventsof a formor text box.

However, with custom events, you have completecontrol over the following:

The name of the event

The parameterspassed to the eventWhenthe event occurs

OOP

16

Page 5: APII 3 OOPb

7/25/2019 APII 3 OOPb

http://slidepdf.com/reader/full/apii-3-oopb 5/16

4/22/20

Class Programming Example

 Type the following two statements into your class:

Private   m_intHeight   As Integer

Public Property   Height() As Integer

  Visual Basic fills in the rest of the proceduretemplate for you(see next slide.

OOP

17

Property Definition Code Example

Public Class clsMyClass

Private m_intHeight As Integer

Public Property Height As Integer

Get

End Get

Set(ByVal value As Integer)

End Set

End Property

End Class  OOP

18

Class Programming Example

CreatingReadableProperties

 The Getconstruct is used to place code that returnsa value for theproperty whenread by a client.

CreatingWritableProperties

 The Set construct is where you place code thatacceptsa new property valuefromclient code.

 Add statements between the Get and End Get and

Set and End Set statements…

OOP

19

Property Definition Code Example

Public Class clsMyClass

Private m_intHeight As Integer

Public Property Height As Integer

Get

Return m_intHeight

End Get

Set(ByVal value As Integer)

 m_intHeight = value

End Set

End Property

End Class  OOP

20

Page 6: APII 3 OOPb

7/25/2019 APII 3 OOPb

http://slidepdf.com/reader/full/apii-3-oopb 6/16

4/22/20

Remember this?Auto-Implemented Property

 A property that is defined by only a single line of code

 Getsand setsvalue of a hiddenprivatefield

 Youdon’thavetocreatea privatemember fieldtoholdthepropertydata.

Example:

Public Property Height As Integer

OOP

21

Remember this?Auto-Implemented Property

 When you declare an auto-implementedproperty, Visual Studio automatically createsahidden private field called a backing fieldthat containsthe property value.

 The backing f ield’s name is an underscore andthe property name.

E.g., if you declare an auto-implemented propertyHeight, itsbacking f ield is_Height

OOP

22

Remember this?Auto-Implemented Property

Now that we have auto-implementedproperties, why do we need to create thelonger property definitions?

Because they allow us to include rangechecking and other validations   on dataassigned to the property.

Also, a ReadOnly property must be fullycoded - it cannot be auto-implemented.

OOP

23

Class Programming Example

 Add the following verification statement to your Set construct(seenext slide for how thecode should now be):

If m_intHeight < 10 Then Exit Property

 This restricts the client to setting the Height propertyto a value greater than or equal to 10.

 If a value less than 10 is passed to the property, theproperty procedure terminates without settingm_intHeight.

 Apart from performing data validationyou can addwhatever code you want and even call otherprocedures.   OOP

24

Page 7: APII 3 OOPb

7/25/2019 APII 3 OOPb

http://slidepdf.com/reader/full/apii-3-oopb 7/16

4/22/20

Class Programming Example

Public Class clsMyClass

Private m_intHeight As Integer

Public Property Height As Integer

Get

Return m_intHeight

End Get

Set(ByVal value As Integer)

If m_intHeight < 10 Then Exit Property

 m_intHeight = value

End Set

End Property

End Class   OOP

25

Creating Read-Only or Write-OnlyProperties

 Read-only properties

 There will be times that you will want to createpropertiesthat can be read but not changed.

E.g. for a Dog object with a property calledNumberOfLegs.

With such an object, you might want to expose theproperty as read-only - code can get the number of legsbut cannot changeit.

 To create a read-only property, use the ReadOnlykeyword to declare the property procedure and

thenremovethe Set...EndSet section.OOP

26

Creating Read-Only or Write-OnlyProperties  For example, i f you wanted the property procedure you just

created to define a read-only procedure, you might declare itlike this:

Public   ReadOnly   Property Height() As Integer

Get

Return m_intHeight

End Get

End Property

 You can create a write-only property, in which the property can

be set but not read (this is rare).   use the keyword WriteOnly  instead of ReadOnly and remove the

Get...End Get section instead of the Set...End Set section.OOP

27

Class Programming ExampleExposing Functions as Methods

 Unlike a property that acts as an object attribute, amethod is a function exposed by an object.

 Methodsare exposed coderoutines.

Amethodcanreturnavalue,butitdoesn’thaveto.

 Methods are easier to create than propertiesbecause they’re defined just as ordinary Sub andFunctionproceduresare.

 To create a method withina class, create a public Sub

or Function procedure.

Like normal Sub and Function procedures, methods def ined 

with Function  return values; methodsdefined with  Sub don’t.OOP

28

Page 8: APII 3 OOPb

7/25/2019 APII 3 OOPb

http://slidepdf.com/reader/full/apii-3-oopb 8/16

4/22/20

Class Programming ExampleExposing Functions as Methods

 Create the following procedure in your class now(enter this code on the line following the   End 

Property statement):

Public Function   AddTwoNumbers(ByVal

intNumber1 As Integer, _ 

ByVal intNumber2 As Integer) As Long

 AddTwoNumb ers = intNumber 1 + intNumber2

End Function

OOP

29

OOP30

Instantiating Objects fromClasses

Class Programming Example31

OOP

Class Programming ExampleInstantiating Objects from Classes

 After you obtain a reference to an object and assign it to avariable, you can manipulate the object by using an objectvariable.

 Click the   ClassExampleForm.vb  Design tab to view the FormDesigner,and add a buttonto the form.

 Set the button’spropertiesasfollows:

OOP

32

Next, double-click the button to access its Click  event, and enterthe code in the following slide…

Page 9: APII 3 OOPb

7/25/2019 APII 3 OOPb

http://slidepdf.com/reader/full/apii-3-oopb 9/16

4/22/20

Class Programming ExampleInstantiating Objects from Classes

‘create a variable of type Object

Dim objMyObject As Object

'create a new object

'clsMyClass is the name of the class to use to derive the object

'(remember, classes are object templates).

objMyObject = New clsMyClass()

'call the AddTwoNumbers method of your class and 

'display the result in a message box

'remember you call a method by its name and 

'give it any parametres it requires

 MessageBox.Show(objMyObject.AddTwoNumbers(1, 2))

OOP

33

Class Programming ExampleInstantiating Objects from Classes

34

NB :

You can also use one statement: 

Dim objMyObject As Object = New clsMyClass() Later we discuss why this is not always advisable.

Class Programming ExampleInstantiating Objects from Classes

 Runthe project by pressing F5

 Click the button:

 Whenfinished, stop the project and save your work.OOP

35

Binding an Object Referenceto a Variable

Class Programming Example36

OOP

Page 10: APII 3 OOPb

7/25/2019 APII 3 OOPb

http://slidepdf.com/reader/full/apii-3-oopb 10/16

4/22/20

Binding an Object Reference to aVariable

 An object can contain any number of properties,methods, and events; every object isdif ferent.

 When you write code to manipulate an object, VisualBasic has to understand the object’s interface, or yourcode won’t work.

 The interface members (the object’s properties,methods, and events) are resolved when an objectvariable is bound to an object.

 Thereare two formsof binding:

 early binding, whichoccursat compiletime

 late binding, whichoccursat runtime.

37

Binding an Object Reference to a VariableLate-Binding an Object Variable

  Whenyou dimensiona variable asdata type Object, you are

late-bindingto the object.

Dim objMyObject As   Object

objMyObject = New clsMyClass()

 MessageBox.Show(objMyObject.AddTwoNumbers(1, 2))

  the binding occurs at runtime when the variable is set to

referencean object.

  The object reference (the addressof the object) will be bound to the

object variable (objMyObject) when the program is executed instead

of when it iscompiled (built).OOP

38

Binding an Object Reference to a VariableLate Binding vsEarly Binding

Note:

You cannot use late binding in a project with OptionStrictturned on.

 Both types of binding have advantages, but earlybinding generally isgenerally better.

 Code that useslate-bound objectsrequiresVBto domore work.

thus a lot of overhead     poor applicationperformance.

 With late binding the compiler cannot check thesyntax of the code manipulatingan object.

39

Class Programming ExampleLate-Binding an Object Variable

 Change the third statement in your code to look like thefollowing (deliberately misspell the AddTwoNumbersmethod):

 MessageBox.Show(objMyObject. AddtoNumbers(1, 2))

  PressF5 to runthe project.

  It runswithout errors.   OOP

40

Page 11: APII 3 OOPb

7/25/2019 APII 3 OOPb

http://slidepdf.com/reader/full/apii-3-oopb 11/16

4/22/20

Class Programming ExampleLate-Binding an Object Variable

 Nobuild errorsas the variable isdeclared AsObject.

 Remember: When you dimension a variable as data type Object,youare late-bindingto the object.

 Visual Basic has no idea what will eventually be placed in thevariable.

 Therefore, it can’t perform any syntax checking at compile timeand just assumes that whatever action you perform with thevariable iscorrect.

 Click the button to create the object and call the method.

 Youget the exceptionshownin thenext slide:

OOP

41

Class Programming ExampleLate-Binding an Object Variable

  Runtime exceptions are more problematic than build errors becausethey’re usually encountered by end users and under varying circumstances.

 When you late-bind objects, it’s easy to introduce these types of problems; therefore, late binding hasa real risk of throwing exceptions.

 Early binding reducesmany of these risks…

OOP

42

Binding an Object Reference to a VariableEarly Binding an Object Variable

 Early binding occurs when you dimension a variable as aspecifictypeofobject, rather thanjust AsObject.

Advantages:

 Speed:considerably faster calls to objectmembers.

 VBcanalso validate the member call at compile time, reducingthechance of errorsin your code.

 The compiler can check for syntax and reference errors in your code sothat many problemsare found at compile time, rather than at runtime.

 Objects, their properties, and their methods appear in

Intell iSensedrop-downlists.

OOP

43

Class Programming ExampleEarly Binding an Object Variable

 Change the Dimstatement in the code you’ve entered to readasfollows:

Dim objMyObject As clsMyClass

 VBdisplays a wavy blue line under the bad method call:

OOP

44

Page 12: APII 3 OOPb

7/25/2019 APII 3 OOPb

http://slidepdf.com/reader/full/apii-3-oopb 12/16

4/22/20

Class Programming ExampleEarly Binding an Object Variable

 VB now knows the exact type of object the variable willcontain; therefore, it canand doesperform syntax checking onall member references.

 Because it can’t find a member with the name AddtoNumbers , itflags thisasa build error.

 Runtheproject by pressing F5

 VBrecognisesthisasa build problem.

OOP

45

Class Programming ExampleEarly Binding an Object Variable

 Place the cursor at the period between the words objMyObjectand AddtoNumbers.

  Deletethe period.

 Type a period oncemore.

 VB displaysan IntelliSense drop-downlist with all the membersof the class:

 SelecttheAddTwoNumbersmember to fix your code.OOP

46

Class Programming ExampleCreating a New Object When Dimensioning aVariable

 You can instantiate a new object on the declarationstatement by includingthekeyword New:

Dim objMyObject As New clsMyClass()

 Hence there is no need for a second statement tocreate a new instance of the object.

 However, if you do this, the variable will alwayscontaina reference to an object.

 If there’s a chance that you might not need theobject, you should probably avoid using the Newkeyword ontheDimstatement...

OOP

47

Class Programming ExampleCreating a New Object When Dimensioning aVariable

 Consider the following:

Dim objMyObject As clsMyClass

If condition Then

objMyObject = New clsMyObject

'Code to use the custom object…

End If

 Instantiating an object takesresources.

  Inthiscode,no object iscreated whencondition isFalse.

 If you were to place the word New on the Dim statement, anew object would be instantiated whenever this code wasexecuted, regardlessof thevalue of condition.

OOP

48

Page 13: APII 3 OOPb

7/25/2019 APII 3 OOPb

http://slidepdf.com/reader/full/apii-3-oopb 13/16

4/22/20

Releasing Object References

Class Programming Example49

OOP

Releasing Object References

 When an object is no longer needed, it should bedestroyed so that all the resourcesused by the objectcan be reclaimed.

 Objects are destroyed automatically when the lastreference to the object is released.

 There are two primary ways to release an objectreference:

 simply let the object variable holding the reference go outof scope.

 set the objectvariable equal to Nothing

OOP

50

Releasing Object References

Variablesare destroyed whenthey go out of scope.

 However, simply letting the object’s variable go outof scope doesnot necessarily meanthat

anobject is fully released and that

all the memory being used by the object is freed.

 Therefore, relying onscope to release objects isn’t agood idea.

 To explicitly release an object, set the objectvariable equal to Nothing:objMyObject = Nothing

OOP

51

Releasing Object References

 When you set an object variable equal toNothing, you’re assured that the objectreference is fully released.

 The object won’t be destroyed, however, if other variablesare referencing it.

 After the last reference is released, thegarbage collector eventually destroys the

object.

OOP

52

Page 14: APII 3 OOPb

7/25/2019 APII 3 OOPb

http://slidepdf.com/reader/full/apii-3-oopb 14/16

4/22/20

Class Programming ExampleReleasing Object References

objMyObject = Nothing

 Add thisstatement to your procedure, right after thestatementthat showsthe message box.

 What if you don’t correctly release objectreferences?Your applicationmight

experienceresourceleaks

the program cannot releaseresourcesit hasacquired.

meaning memory whichisno longer needed isnot released.

becomesluggish,and

consumemore resourcesthan it should.OOP

53

Objects Lifetime54

OOP

Objects Lifetime

 An object created from a class exists as long as avariable holdsa reference to it.

 Fortunately, the .NET Framework keeps track of thereferencesto a given object; you don’t have to worryabout thiswhencreating or using objects.

 When all the references to an object are released,theobject is flagged and eventually destroyed by thegarbage collector.

 Understanding the lifetime of objects is important…

OOP

55

Objects Lifetime

 An object is created (and hence referenced) when anobject variable is declared by the keyword Newe.g.:

Dim objMyObject = New clsMyClass()

 An object is created (and hence referenced) when anobject variable is assigned an object by the keywordNewe.g.:

objMyObject = New clsMyClass()

 An object is referenced when an object variable isassigned an existing object e.g:

objThisObject = objThatObjectOOP

56

Page 15: APII 3 OOPb

7/25/2019 APII 3 OOPb

http://slidepdf.com/reader/full/apii-3-oopb 15/16

4/22/20

Objects Lifetime

 An object reference is released when an objectvariable is set to Nothing e.g.:

objMyObject = Nothing

 An object is destroyed sometime after the lastreference to it isreleased.

 This ishandled by the garbage collector.

 Youshould explicitly release anobject reference.

 Only when all references to an object are released istheobject f lagged for destruction and the resourcesitusesare reclaimed.

OOP

57

Do the following tasks on your own …

Tasks58

OOP

Tasks

 Add a new propertyto your classcalled DropsInABucket .

 Make thisproperty a  Long , and set it up so that client code canread the property value but not set it.

 Finally, add a button to the form that, when clicked, shows amessage box with the value of the property (it will be 0 bydefault).:

 When this is working, modify the code so that the propertyalwaysreturns1,000,000.

OOP

59

Tasks

 Add a button to your formthat createstwo object variablesof type clsMyClass().

 Use the  New  keyword to instantiate a new instance of the classinone of the variables.

 Thenset the second variable to reference the same object andprint the contentsof the Height property to 2 dif ferent labels:

OOP

60

After clicking… 

Page 16: APII 3 OOPb

7/25/2019 APII 3 OOPb

http://slidepdf.com/reader/full/apii-3-oopb 16/16

4/22/20

Tasks

 An interface can be said to be a set of exposed functionality (properties, methods,and events).

 When writing your programs you mayunintentionally write infiniterecursiveevents.

 Read up on recursive events and writeexample code in Visual Basic demonstratingthe conceptsyou learn.

OOP

61