Вы находитесь на странице: 1из 48

F5227

VB.NET PROGRAMMING
TOPIC 4

OOP in VISUAL BASIC.NET

PART 1 CLASSES, OBJECTS AND METHODS

A Real world example


Object-Oriented Development Concepts A real object-oriented programming language supports three basic concepts: encapsulation, polymorphism, and inheritance. It is easier to understand these concepts by providing a parallel to real-world. A Real-World Example Think about an object that everyone is familiar with, a TV. Could you explain every detail of how a show is broadcast and displayed on TV? Probably not. How is a TV built? Somewhere someone has designed a set of blueprints that specifically outline the necessary parts and their configuration. These blueprints would specify the internal and external characteristics that define how the TV would operate. There are a great many variations in television design. If you had a set of blueprints for the latest 65-inch HDTV, you would have the information required to build a great TV, but you couldnt watch a program on the blueprints. The TV would not come set to the exact station you would want when you receive it. It comes with an interface in the form of a remote control. This interface allows the user to set certain of the TVs characteristics to specific values.

Object Oriented concept


In Visual Basic .NET you use a class to describe the properties and actions associated with an object in the same manner as a blueprint describes the properties and functionality of a TV. A developer should not allows access to the properties of a class except by specific routines that the developer creates. These routines are referred to as methods of the class. A class does not serve as a functioning version of the item you are creating. The class must be built just as your TV is assembled. When you wish to create a functioning version of the class, you must create an object. While the computer does not have an assembly line to create an object, it does have to allocate the memory required for the object and initialize any variables. This process of creating an object from a class is known as instantiating an object.

Object

Objects are the basic building blocks of a program.

Objects included in Visual Basic .NET make the development of complex applications easier because you do not have to concern yourself with the creation of objects and their properties. Visual Basic .NET allows you to create your own objects both by code and visually from existing objects contained within Visual Basic .NET.

Illustrating: Class versus Object


CLASSES

OBJECT OF EACH CLASS

Adam Customer Annalisa

Daniel

Order

Order_123 Order_656 Order_234

Encapsulation

Encapsulation enables the programmer designing the class to dictate what types of operations are permissible upon a class without permitting other programmers access to the inner workings of the class. The class designer allows other programmers to have the complexity of a class hidden and ensures that other programmers can only use the class in ways intended by the programmer designing the class. You have used objects like text boxes, labels, and buttons without knowledge of their internal workings.

The properties and events accessed only allowed you to manipulate the objects in ways predetermined by the developers of the objects.

Polymorphism

The concepts of having one name but a different behavior depending upon the object it belongs to is known as polymorphism. Many of the controls that you have built your application from have properties, methods, or events with the same name but take on a slightly different meaning from control to control. You have been using polymorphism when you perform the basic mathematical operations. Regardless of the data type you wish to perform addition or subtraction on, you use operators like + or -. You do not require a different operator to perform an addition for each data type. When you design objects that have similar functions, it is helpful to design them with polymorphism in mind.

Inheritance

One of the keys to efficient development of applications is the ability to reuse the code that you previously developed.

One way programmers accomplish this is to cut and paste code from one project to another.
A better method, inheritance, is to build new classes from previous ones without modifying the original code. If you use the former method and then later discover a bug in the original code, you must go back and modify the code in all the classes you copied the bug into. With inheritance, if you modify the original class, all the classes based on that change would be updated automatically. The other problem, although not quite as severe, is the waste of a lot of unnecessary disk space by having multiple copies of the source code each time you copy it.

Using Built-In Objects

Visual Basic .NET comes with many built-in objects ready for you to use. Not all objects are visual in nature. There are many ways of adding objects to your application. The most intuitive way to add an object to your application is to drag a predefined object onto your form. This only works with objects built into the toolbox. There are other ways you can declare and instantiate objects.

Built in Classes 1: String Class

You are already familiar with declaring variables of the type String Dim strName As String

When you declare an object in this way, it is considered a structure or value type variable. There is only a subtle difference between using value and reference type objects. You only need to concern yourself with the difference in declaring, allocating, and reallocating value type objects from reference type objects. Value type variables are automatically reallocated when the routine they are declared within is exited.

String Class.. cont

There are a great many routines that can be executed upon the data stored in the String built into the String class. These routines are commonly referred to as methods of the class. In general, methods come in two varieties. Some methods and functions perform a series of tasks and pass a value back to the calling routine. Other methods and subroutines will perform a series of tasks but not pass a value back. To access a lit of methods of a class, just type a period after the objects name.

Built in methods for String Class


Here is a list of some of the methods available for the String class. All of the String class methods are functions. They return a value that is the result of the method. In all of these methods, the original value of the String is not changed in any way. 1) Method Name: ToUpper Method Description: Returns the String that is passed in all uppercase letters. Common Uses: While ToUpper can be used when the desired output is required to be all in uppercase letters, it is commonly used when you wish to validate data entered by a user against a given string. Syntax: String = strStringVariable.ToUpper()

Built in methods for String class..


Examples:
Invoke Method
strStringVariable = Input String strStringVariable.ToUpper() strStringVariable = all lowercase strStringVariable.ToUpper() strStringVariable = ALL UPPERCASE strStringVariable.ToUpper() strStringVariable = UpPeR AnD lOwErCaSE strStringVariable.ToUpper()

Return Value
INPUT STRING ALL LOWERCASE ALL UPPERCASE UPPER AND LOWERCASE

Built in methods for String class..


2) Method Name: ToLower Method Description: Returns the String that is passed converted to all lowercase letters. Common Uses: ToLower is very similar to ToUpper. While is it more comm to use ToUpper for data validation, ToLower can be used equally well. Syntax: String = strStringVariable.ToLower() Examples: Invoke Method Return Value
strStringVariable = Input String strStringVariable.ToLower() strStringVariable = all lowercase strStringVariable.ToLower() strStringVariable = ALL UPPERCASE strStringVariable.ToLower() strStringVariable = UpPeR AnD lOwErCaSE strStringVariable.ToLower() input string all lowercase all uppercase upper and lowercase

Built in methods for String class..


3) Method Name: Trim Method Description: Returns a String with the same content, except the leading and trailing spaces are removed. Common Uses: Often when data is gathered, additional spaces may exist before the first noncharacter or after the last nonblank character. It is good practice to remove these so that data may be presented cleanly. Syntax: String = strStringVariable.Trim() Examples: Invoke Method Return Value
strStringVariable = InputString strStringVariable.Trim() strStringVariable = InputString strStringVariable.Trim() strStringVariable = InputString strStringVariable.Trim() strStringVariable = Input String strStringVariable.Trim() InputString InputString InputString Input String

Built in methods for String Class..


4) Method Name: Length Method Description: Returns the number of characters contained in a String Common Uses: Length is used to determine the size of a String. Syntax: Integer = strStringVariable.Length() Examples:
Invoke Method strStringVariable = Inconceivable strStringVariable.Length() strStringVariable = Iocaine Powder strStringVariable.Length() Return Value 13 14

strStringVariable = Hello, my name is Inigo Montoya. You killed my father. Prepare to die. strStringVariable.Length()
strStringVariable = strStringVariable.Length()

70

Built in methods for String Class..


5) Method Name: Substring Method Description: Returns a specific number of characters from a String allowing you to indicate where to start and how many characters to return. The first parameter is an Integer indicating the starting position of the characters to return. The second parameter is optional and indicates the number of characters to return. If the second parameter is left out, all characters from the starting position are returned. Common Uses: Often you wish to extract a portion of a String for use separately from the rest of the String. This is often used when working with fixed-width data files. Syntax: String = strStringVariable.Substring(Integer (Starting Position), Optional Integer(Length))

Example:
Invoke Method Return Value

strStringVariable = This is the String strStringVariable.Substring(5,2)


strStringVariable = This is the String strStringVariable.Substring(8,3)

is
the

strStringVariable = This is the String strStringVariable.Substring(12,4)


strStringVariable = This is the String strStringVariable.Substring(7)

Stri
the String

Built-in classes 2: MessageBox Class

A message box can be used to display a message and to get a response MessageBox class

Member of System.Windows.Forms namespace Has a single method named Show Creates an instance of MessageBox class Makes a message box appear

Show method

Built in classes 2: MessageBox class..

Show method can receive up to four arguments

First argument Message to be displayed Second argument Caption to be displayed Third argument Specifies the buttons to be displayed Fourth argument Specifies the type of icon displayed

Built-in method for MessageBox class: Show

Return value obtained from Show method

Indicates which button was clicked by user Is of data type DialogResult Can be compared to specific values using an If statement

Creating your own classes

Classes in Visual Basic .NET can be created in a few ways. One way is to crate a class in code. A class can be thought of as being composed of three sets of definitions. To define a class and all of its attributes and methods, you enclose all of the contents using the following syntax: Public Class ClassName 'Properties definitions go here 'Property Get/Set statements go here 'Methods go here End Class

Creating your own classes .. cont


Public Class are keywords that indicate to Visual Basic .NET that you are creating a class. ClassName indicates the name of the class. A class name follows the same rules as when you create a variable name. End Class are keywords that indicate to Visual Basic .NET that you have finished specifying the creation of a class. The property definitions of a class that you define are conceptually the same as properties in the objects you are already familiar with. The property Get/Set statements allow you to detail how you will allow users of the class to access the individual properties defined for the class. Methods of a class allow you to write subroutines and functions that have access to all of the properties defined within the class. Methods are how other objects and routines interact with the class you are defining.

Creating your own classes.. cont


Here are the steps entailed in creating the Counter class which allows you to create an object that will store an Integer starting at 1 and incremented by 1: Step 1: Select Add Class from the Project menu. The window will appear:

Creating your own classes.. cont


Step 2: Specify the name of the class by changing Class1.vb to Counter.vb. Then click on the Open button. Observe the changes to the development environment. The keywords Public Class and End Class enclose the Counter class and the new file is included in the Solution Explorer:

Creating your own classes.. cont

Step 3: You must specify the properties of the class. Properties are in essence the variables of the class. For the Counter class, only one value must be stored, the current state of the counter. Therefore, only one property is required. An Integer property must be created to store the current value of the counter. The property is declared within the class definition. A property is defined with the following syntax:

Scope PropertyName As Datatype

The Scope of a property determines how visible this property is to other parts of the application. The scope can be Public, Private, or Protected. A Public scope gives the entire application access to the property, while a Private scope only allows methods from the class the property is defined within to have access to it. The Protected scope deals with more advanced concepts in object-oriented development and will be skipped for now. The rules for specifying a data type for a property are the same as for declaring a variable. Therefore, a data type can be an Integer, Single, String, text box, and so on. Declare all of the properties for your Counter class:

Creating your own classes.. cont


Get and Set In order to allow properties to be accessed, Visual Basic .NET provides special functions to allow the developer to access each of the properties. If you do not want a property to be accessed directly, you could leave out the property function and it would not be accessible outside the class. The functions are called Get and Set. Get allows you to specify what property variable is returned when the property is accessed. Set allows you to specify what property variable is set when you assign a value to the property. The syntax for the Get and Set routines for a property are as follows:

Public Property PropertyName() As Datatype Get Return PropertyVariableName End Get Set PropertyVariableName = Value End Set End Property The PropertyName is the name of the property as it appears to the developer. The PropertyVariableName is the name of the property variable accessible only within the class and its methods. If there are no rules restricting the values that can be set to a property, then your Set statement can simply assign the quantity being passed in the Value parameter to the Private property.

Get and Set Continued The Get and Set routines for the Counter class are as follows: Public Property CurrentValue() As String Get Return mintCurrentCount End Get Set(ByVal Value As String) If (Value = 0) Then mintCurrentCount = Value Else MsgBox("You have attempted to set the counter to a value " &_ " other than 0") End If End Set End Property

Writing method

You need the ability to perform operations upon the properties stored within the class. A method is an easy way to accomplish this. By providing public methods to a class, you can control the way developers access the properties you specify. You have two choices as to the type of method that you can create. The simplest is a subroutine. The syntax for writing a simple subroutine method is as follows:

Public Sub MethodName() 'Body of Method End Sub

Writing method cont


The keywords Public Sub specify the beginning of a subroutine that will be called MethodName. A subroutine can be named using the same rules as were used for declaring a variable. The parentheses following MethodName are required. The body of the method will be instructions that you wish to execute when the method is called. The keywords End Sub specify the end of the subroutine.

Example: You want to create a method that allows the user to call a Reset routine that sets the counter back to 0: 'Method to reset the counter to 0 Public Sub Reset() mintCurrentCount = 0 End Sub Here is the code to increment or decrement the counter:
'Method to add 1 to the counter Public Sub Increment() mintCurrentCount += 1 End Sub 'Method to subtract 1 from the counter Public Sub Decrement() mintCurrentCount -= 1 End Sub

Writing method with parameter


Often you will wish a method to provide different functionality depending upon parameters that are provided. If only one parameter were to be passed to a subroutine, the syntax would be as follows: Public Sub MethodName(ParameterName As Datatype) 'Body of Method End Sub The only difference between the declaration of a method with parameters and one without is the addition of code in between the parentheses. This code indicates the name and type of the parameter that will be passed to the method. The parameter name is used to reference the parameter within the method. It can be named using the same rules as were used for declaring a variable. Once a parameter is declared, it can be accessed within the method just as any of the properties of the class can.

Writing method with parameter ..cont


The code to create a method called LargeIncrement that accepts a parameter called intAmount of the Integer type is as follows: 'Method to allow increments by more than 1 to the counter Public Sub LargeIncrement(ByVal intAmount As Integer) mintCurrentCount += intAmount End Sub

Writing methods with parameter


If more than one parameter is to be passed, you can create a method with as many parameters as you wish by separating the individual parameters with commas. The following code shows you the syntax for creating a method with three parameters: Public Sub MethodName(ParameterName As Datatype, _ ParameterName As Datatype, _ ParameterName As Datatype) 'Body of Method End Sub

Creating object from a class


When you define a class, all that you have accomplished is creating a model for declaring objects. In order to create an object of a class you must instantiate it. You can use the following syntax: Dim objName As New ClassName() The statement will declare and instantiate an object called objName of the class ClassName. If you do not wish to declare and instantiate an object in the same statement, you can separate them. Sometimes this is desirable, because you may not require the object in all cases and it would be a waste of resources to allocate it early.

Creating object from a class.. cont


The syntax for declaring and instantiating an object separately is as follows: Dim objName As ClassName 'Other code goes here objName = New ClassName() If you wanted to declare an Employee object called JeffSalvage, you could use the following code: Dim JeffSalvage As Employee 'Other code goes here JeffSalvage = New Employee()

Setting properties to an object

Once an object has been instantiated, you will want to set its individual properties. With an object declared from code you do not have the option of using the Properties window. You need another syntax:

objName.PropertyName = PropertyValue

Setting properties to an object.. cont


To declare an object JeffSalvage and set all the properties to the values in the following chart, you would require the following code:
Property FirstName LastName MondayHours TuesdayHours WednesdayHours Value Jeff Salvage 7 9 8.5

ThursdayHours
FridayHours HourlyWage

7.5
8 125.00

Dim JeffSalvage As New Employee() JeffSalvage.FirstName = "Jeff" JeffSalvage.LastName = "Salvage" JeffSalvage.MondayHours = 7 JeffSalvage.TuesdayHours = 9 JeffSalvage.WednesdayHours = 8.5 JeffSalvage.ThursdayHours = 7.5 JeffSalvage.FridayHours = 8 JeffSalvage.HourlyRate = 125

Calling a method
Once an object has been instantiated, its methods can be called. Calling a method is often referred to as invoking a method and can be accomplished using the following syntax: objName.MethodName() Example: To invoke the method OutputWeeklyPay of the object JeffSalvage, use the following code: JeffSalvage.OutputWeeklyPay() To invoke the method OutputWeeklyPay of the object JeffSalvage with the parameter Monday, use the following code: JeffSalvage.OutputWeeklyPay(Monday)

Overriding method

Overloading a method is creating the same method many times each time with different parameters These methods can be called uniquely depending upon the parameters we pass.

Overriding method: Example


Public Function Total() As Integer ' No Arguments passed Total = ((mintAdults * mintAdultRates) + (mintKids * mintKidRates)) * mintNumDays End Function

Public Function Total(ByVal mintPercent As Integer) As Integer ' Overloaded with one argument Total = ((mintAdults * mintAdultRates) + (mintKids * mintKidRates)) * mintNumDays Total = Total - ((Total) * mintPercent / 100) End Function Public Function Total(ByVal mintPercent As Integer, ByVal mintSeasonalDiscount As Integer) As Integer 'Overloaded with two argument Total = ((mintAdults * mintAdultRates) + (mintKids * mintKidRates)) * mintNumDays Total = Total - ((Total) * mintPercent / 100) Total = Total - ((Total) * mintSeasonalDiscount / 100) End Function

Exercise
1) Match the following items to the closest example. A inheritance B polymorphism C encapsulation D instantiation E class 1 When a function takes on different meanings based upon what object is being used. 2 The hiding of the details of the implementation from a developer. 3 The ability to create a new class based on the definition of an existing one. 4 The blueprint of an object. 5 The creation of an object from a class.

Exercise
2) Which of the following calls to the methods of the String class are correct? A strStringVariable.ToUpper() B strStringVariable.ToUpper(This will work) C strStringVariable.Length(10) D strStringVariable.Trim() E strStringVariable.SubString(This will work, 10) F strStringVariable.SubString(This will work, 10, 2) G strStringVariable.SubString(10) H strStringVariable.SubString(10, 2) I strStringVariable.GiveMeAnA()

Exercise
3) What is the output of the following code? a.

strStringVariable = "Do or do not, there is no try." MsgBox(strStringVariable.ToUpper())

b. strStringVariable = "Do or do not, there is no try." MsgBox(strStringVariable.SubString(14))


c.

strStringVariable = "Do or do not, there is no try." MsgBox(strStringVariable.Length().ToString)

Exercise
4) Given the following definitions of three methods, show which of the following method calls are valid:
Private Sub DrillMethod1(ByVal intDrillValue As Integer, _ ByVal strDrillValue As String) End Sub Private Sub DrillMethod2(ByVal strDrillValue As String, _ ByVal intDrillValue As Integer) End Sub Private Sub DrillMethod3(ByVal strStringValue As Integer, _ ByVal intIntegerValue As String) End Sub

Dim Dim Dim Dim

intVal1 As Integer strVal2 As String intVal3 As Integer sngVal4 As Single

a) b) c) d) e) f)

DrillMethod1(intVal1, strVal2) DrillMethod1(strVal2, intVal1)

DrillMethod2(intVal1, intVal3)
DrillMethod2(sngVal4, intVal1) DrillMethod2(strVal2, intVal1) DrillMethod3(intVal1, strVal2)

Вам также может понравиться