OOP with VB

download OOP with VB

of 7

Transcript of OOP with VB

  • 8/2/2019 OOP with VB

    1/7

    OOP with VB

    Constructors

    A constructor is a special member function whose task is to initializethe objects of it's class. This is the first method that is run when aninstance of a type is created. A constructor is invoked whenever anobject of it's associated class is created. If a class contains aconstructor, then an object created by that class will be initializedautomatically. We pass data to the constructor by enclosing it in theparentheses following the class name when creating an object.Constructors can never return a value, and can be overridden toprovide custom intitialization functionality. In Visual Basic we createconstructors by adding a Sub procedure named New to a class. Thefollowing code demonstrates the use of constructors in Visual Basic.

    Module Module1

    Sub Main()

    Dim con As New Constructor(10)WriteLine(con.display())'storing a value in the constructor by passing avalue(10) and calling it with the'display methodRead()

    End Sub

    End Module

    Public Class ConstructorPublic x As Integer

    Public Sub New(ByVal value As Integer)'constructorx = value'storing the value of x in constructorEnd Sub

    Public Function display() As IntegerReturn x

    'returning the stored valueEnd Function

    End Class

    Destructors

    A destructor, also know as finalizer, is the last method run by a class.

    http://www.startvbdotnet.com/oop/constructor.aspxhttp://www.startvbdotnet.com/oop/constructor.aspx
  • 8/2/2019 OOP with VB

    2/7

    Within a destructor we can place code to clean up the object after it isused, which might include decrementing counters or releasingresources. We use Finalize method in Visual Basic for this and theFinalize method is called automatically when the .NET runtime

    determines that the object is no longer required. When working withdestructors we need to use the overrides keyword with Finalizemethod as we will override the Finalize method built into the Objectclass. We normally use Finalize method to deallocate resources andinform other objects that the current object is going to be destroyed.Because of the nondeterministic nature of garbage collection, it isvery hard to determine when a class's destructor will be called. Thefollowing code demonstrates the use of Finalize method.

    Module Module1

    Sub Main()Dim obj As New Destructor()End Sub

    End Module

    Public Class Destructor

    Protected Overrides Sub Finalize()Write("hello")Read()End Sub

    End Class

    When you run the above code, the word and object, obj of class,destructor is created and "Hello" is displayed. When you close theDOS window, obj is destroyed.

    Methods

    A Method is a procedure built into the class. They are a series of statements that areexecuted when called. Methods allow us to handle code in a simple and organizedfashion. There are two types of methods in VB .NET: those that return a value(Functions) and those that do not return a value (Sub Procedures). Both of them arediscussed below.

    Sub Procedures

  • 8/2/2019 OOP with VB

    3/7

    Sub procedures are methods which do not return a value. Each time when the Subprocedure is called the statements within it are executed until the matching End Subis encountered. Sub Main(), the starting point of the program itself is a subprocedure. When the application starts execution, control is transferred to Main Subprocedure automatically which is called by default.

    Example of a Sub Procedure

    Module Module1

    Sub Main()'sub procedure Main() is called by defaultDisplay()'sub procedure display() which we are creatingEnd Sub

    Sub Display()System .Console.WriteLine("Using Sub Procedures")

    'executing sub procedure Display()End SubEnd Module

    The image below displays output from above code.

    Functions

    Function is a method which returns a value. Functions are used to evaluate data,make calculations or to transform data. Declaring a Function is similar to declaring aSub procedure. Functions are declared with the Function keyword. The following codeis an example on Functions:

    Imports System.Console

    http://www.startvbdotnet.com/language/methods.aspx#%23http://www.startvbdotnet.com/language/methods.aspx#%23http://www.startvbdotnet.com/language/methods.aspx#%23http://www.startvbdotnet.com/language/methods.aspx#%23
  • 8/2/2019 OOP with VB

    4/7

    Module Module1

    Sub Main()Write("Sum is" & " " & Add())'calling the functionEnd Sub

    Public Function Add() As Integer'declaring a function addDim i, j As Integer'declaring two integers and assigning values to themi = 10

    j = 20Return (i + j)'performing the sum of two integers and returning it's valueEnd Function

    End Module

    The image below displays output from above code.

    Calling Methods

    A method is not executed until it is called. A method is called by referencing it'sname along with any required parameters. For example, the above code called theAdd method in Sub main like this:Write("Sum is" & " " & Add()) .

    Method Variables

    Variables declared within methods are called method variables. They have methodscope which means that once the method is executed they are destroyed and theirmemory is reclaimed. For example, from the above code (Functions) the Add method

  • 8/2/2019 OOP with VB

    5/7

    declared two integer variables i, j. Those two variables are accessible only within themethod and not from outside the method.

    Parameters

    A parameter is an argument that is passed to the method by the method that calls it.Parameters are enclosed in parentheses after the method name in the methoddeclaration. You must specify types for these parameters. The general form of amethod with parameters looks like this:

    Public Function Add(ByVal x1 as Integer, ByVal y1 as Integer)------------Implementation------------End Function

    Understanding Objects

    Object-oriented programming has been a technical buzzword for quite some time, but as far as Visual

    Basic programmers are concerned, it became a reality only with Visual Basic .NET (no previous

    version of Visual Basic was a true OO language). Almost everywhere you lookthe Web, publications,

    booksyou read about objects. What exactly is an object? Strictly speaking, an object is a

    programming structure that encapsulates data and functionality as a single unit and for which the only

    public access is through the programming structure's interfaces (properties, methods, and events). In

    reality, the answer to this question can be somewhat ambiguous because there are so many types of

    objectsand the number grows almost daily. However, all objects share specific characteristics, such

    as properties and methods.

    The most commonly used objects in Visual Basic .NET are the form object and the control object.

    Earlier hours introduced you to working with forms and controls and even showed you how to set form

    and control properties. In your Picture Viewer project from Hour 1, for instance, you added a picture

    box and two buttons to a form. Both the PictureBox and the Button controls are control objects , but

    each is a specific type of control object. Another, less-technical example uses pets. Dogs and cats are

    definitely different entities (objects), but they both fit into the category of Pet objects. Similarly, textboxes and buttons are each a unique type of object, but they're both considered a control object. This

    small distinction is important.

    COLLECTIONS

    Collection Classes

  • 8/2/2019 OOP with VB

    6/7

    ==============================i) ArrayListii) HashTableiii)SortedListiv) Queue and Stack

    ArrayList:==============================The ArrayList is a collection class that models a dynamic array, whose size increases asrequired when new objects are added to the array.Namespace : System.CollectionsImplementing Interfaces : ICollection, IList, ICloneable, IConvertible

    Characteristics:==============================i) To store dynamic data use the arraylist class. So it is compact memory usage.ii) The search for an item in an arraylist is performed sequentially. So it is slow.iii)Type of Access is indexed.

    HashTable:==============================A HashTable is a collection of key-value pairs implemented using a hash table algorithm.Namespace : System.CollectionsImplementing Interfaces : ICollection, IDictionary

    Characteristics:==============================i) Search is very fast.ii) HashTables are big and fast.iii)High Memory usage.iv) Type of Access is using the hash of a key value.

    SortedList:==============================A SortedList is a collection class that holds a set of key-value pairs.Namespace : System.CollectionsImplementing Interfaces : ICollection, IDictionary

    Characteristics:==============================i) A Sorted List may not contain duplicate keys. A HashTable can have duplicate keys.ii) Search is fast.iii)Medium Memory usage.iv) Type of Access is using the index and key value.

    Queue and Stack:==============================i) Queue uses a First-In-First-Out (FIFO) Algorithm.ii) Stack uses a Last-In-First-Out (LIFO) Algorithm.

    Methods of Queue:==============================i) Enqueue (Add an item)ii)Dequeue (Remove the first item)

    Methods of Stack:==============================i) Push (Add an item)ii)Pop (Remove the last item)

  • 8/2/2019 OOP with VB

    7/7