Difference between revisions of "Object Oriented Programming with Visual Basic"

From Techotopia
Jump to: navigation, search
(Defining and Calling Methods)
Line 82: Line 82:
 
Now that we have defined the properties of our class, the next task is to define methods that will give us access to our data.
 
Now that we have defined the properties of our class, the next task is to define methods that will give us access to our data.
  
== Defining and Calling Methods ==
+
== Defining Class Methods ==
  
 
Since we have declared our our class data properties to be private, we need to provide methods which will give us access to those properties from our code. This is achieved using Get and Set methods. The syntax for get and Set methods is as follows:
 
Since we have declared our our class data properties to be private, we need to provide methods which will give us access to those properties from our code. This is achieved using Get and Set methods. The syntax for get and Set methods is as follows:
Line 135: Line 135:
  
 
When called, the above function subtracts the account fee from the balance, assigns thje new balance  the intBalance variable and returns the new total.
 
When called, the above function subtracts the account fee from the balance, assigns thje new balance  the intBalance variable and returns the new total.
 +
 +
Now that we have added some functionality to our class it is time to instantiate objects from the class ''blueprint''.
  
 
== Subclassing in PHP ==
 
== Subclassing in PHP ==

Revision as of 17:53, 8 August 2007

Visual Basic provides extensive support for developing object-oriented Windows applications. The subject area of object oriented programming is, however, large. Entire books can, and indeed have, been dedicated to the subject. As such, a detailed overview of object oriented software development is beyond the scope of Visual Basic Essentials. Instead, we will introduce the basic concepts involved in object oriented programming and then move on to explaining the concept as it relates to Visual Basic application development.


Contents


What is an Object?

An object is a self-contained piece of functionality that can be easily used, and re-used as the building blocks for a software application.

Objects consist of data variables and functions (called methods) that can be accessed and called on the object to perform tasks. These are collectively referred to as members.

What is a Class?

Much as a blueprint or architect's drawing defines what an item or a building will look like once it has been constructed, a class defines what an object will look like when it is created. It defines, for example, what the methods will do and what the member variables will be.


How is an Object Instantiated from a Class?

The process of creating an object from the class 'blueprint' is called instantiation. Essentially, you instantiate an instance of the class and give that instance a name by which you will refer to it when accessing members and calling methods. You can create as many object instances of a class as you desire. Objects are instantiated from a class using the new keyword. Visual Basic provides two ways to instantiate an object from a class. These two alternatives are known as late-binding and early binding.

Late binding occurs when the assignment of the object to the variable occurs at run-time when execution reaches the code where the object is created. There are drawbacks to this approach in that any syntax checking is not performed until the application runs because the compiler has no way of checking whether you are referencing valid class members, resulting in potential run-time exceptions. Another disadvantage is that execution can be slowed when using late-binding since much of the work performed by the compiler when using early binding has to be performed at runtime.

Late binding is achieved using the new keyword as follows:

Dim objBankAccount As Object

objBankAccount = New clsBankAccount()

Early binding, on the other hand, has none of the draw backs of late-binding. The compiler performs syntax checks to ensure the object is being used correctly and execution speed is increased because the binding takes place at compile time - not at run-time.

Early binding is performed as follows:

Dim objBankAccount As clsBankAccount

objBankAccount = New clsBankAccount


It is also possible to instantiate the object at the same time that it is declared:

Dim objBankAccount As New clsBankAccount()

What is sub-classing?

It is possible to build classes that are derived from other classes, extending the functionality of the parent class to make it specific to a particular requirement. For example you might have a vehicle class which contains the attributes common to all vehicles, and a subclass called car which inherits all the generic vehicle attributes but adds some its own car specific methods and properties.

Defining a Visual Basic Class

Before an object can be instantiated we first need to define the class 'blueprint' for the object. In this chapter we will create a bank Account class to demonstrate the concepts of Visual Basic object oriented prorgamming.

Being by starting Visual Studio and creating a new Windows Application named vbObjects. Once the project opens, select the Project... menu and select Add class.... In the Add New Item dialog, name the new class file clsBankAccount.vb and click on the Add button.

Visual Studio will now add a new tab to code area for the new class file containing the following class declaration:

Public Class clsBankAccount

End Class

We have now defined a class. The next step is add some functionality to the class.

Creating Visual Basic Class Properties

Class members or properties are essentially variables embedded into the class. Members can be Public or Private.

Public members can be accessed from outside the object. Private members can only be accessed by methods contained in the class. This the key to what is called data encapsulation. Object-oriented programming convention dictates that data should be encapsulated in the class and accessed and set only through the methods of the class (typically called getters and setters).

We can now extend our BankAccount class to add member variables to hold the account name and number. True to the concept of data encapsulation we will be creating methods to access these values later, so will mark them as Private:

Public Class clsBankAccount
    Private strAccountNumber As String
    Private strAccountName As String
    Private intBalance As Integer
    Private accountFee As Integer = 5

End Class

Now that we have defined the properties of our class, the next task is to define methods that will give us access to our data.

Defining Class Methods

Since we have declared our our class data properties to be private, we need to provide methods which will give us access to those properties from our code. This is achieved using Get and Set methods. The syntax for get and Set methods is as follows:

Public Property propertyName() As datatype
   Get
     .... Code to return property value
   End Get

   Set(ByVal value As datatype )
     .... Code to return property value
   End Get

To demonstrate this we will add to our class to provide methods to get and set the account number and name. Note that after you type in the Public Property line of the declaration, Visual Studio automatically creates a template for the Get and Set methods, which should be filled in as follows:

Public Class clsBankAccount
    Private strAccountNumber As String
    Private strAccountName As String
    Private intBalance As Integer
    Private accountFee As Integer = 5

    Public Property AccountName() As String
        Get

        End Get
        Set(ByVal value As String)

        End Set
    End Property

    Public Property Balance() As Integer
        Get
            Return intBalance
        End Get
        Set(ByVal value As Integer)
            intBalance = value
        End Set
    End Property
End Class
End Class

Now that we have defined our getter and setter methods we can add our own method to perform task. This is the same as writing a Visual Basic function. The purpose of our method will be to subtract the account fee from the current balance:

    Public Function subtractFee() As Integer
        intBalance = intBalance - intAccountFee
        Return intBalance
    End Function

When called, the above function subtracts the account fee from the balance, assigns thje new balance the intBalance variable and returns the new total.

Now that we have added some functionality to our class it is time to instantiate objects from the class blueprint.

Subclassing in PHP

Once a class has been defined it is possible to create a new class derived from it that extends the functionality of the original class. The parent class is called the superclass and the child the subclass. The whole process is referred to as 'subclassing.

A subclass of a class can be defined using the extends keyword when declaring the subclass. For example we might choose to create a subclass of of our bankAccount class called savingsAccount which defines an interest bearing type of account:

<?php
class savingsAccount extends bankAccount {

         private $interestRate = 5;

}

The important point to note here is that savingsAccount inherits all the members and methods of bankAccount and adds a new member (the interest rate).

We can extend the class further by adding a new method to return the interest rate:

<?php
class bankAccount {

   private $accountNumber;
   private $accountname;

   public function __construct($acctNumber, $acctName) {
        $this->accountNumber = $acctNumber;
        $this->accountname = $acctName;
   }

   public function __destruct() {
   }

   public function setAccountNumber($acctNumber)
   {
       $this->accountNumber = $acctNumber;
   }

   public function setAccountName($acctName)
   {
       $this->accountName = $acctName;
   }

   public function getAccountName()
   {
       return $this->accountName;
   }

   public function getAccountNumber()
   {
       return $this->accountNumber;
   }

}


class savingsAccount extends bankAccount {

   private $interestRate = 5;

   public function getInterestRate()
   {
       return $this->interestRate;
   }

}

        $mySaveObj = new savingsAccount('246810', 'Morgan Freeman');

        echo "Savings Account Number is " . $mySaveObj->getAccountNumber() . '<br>';

        echo "Interest Rate = " . $mySaveObj->getInterestRate() . '<br>';
?>

PHP Object Serialization

One of the interesting features of object oriented programming is the ability to take a snapshot of the current state of an object and then save that object to a file, or even transmit it over a network to another process where it will be re-activated. This concept is known in the object oriented world as object serialization.

All objects have built-in method called __sleep that is called before serialization. If you need your object to perform any housekeeping before being serialized you will need to override this method.

An object is serialized using the serialize() function and unserialized, not surprizsingly, using the unserialize() function. As an example we can serialize our bankAccount object:

<?php
class bankAccount {

   private $accountNumber;
   private $accountname;

   public function __construct($acctNumber, $acctName) {
        $this->accountNumber = $acctNumber;
        $this->accountname = $acctName;
   }

   public function __destruct() {
   }

   public function setAccountNumber($acctNumber)
   {
       $this->accountNumber = $acctNumber;
   }

   public function setAccountName($acctName)
   {
       $this->accountName = $acctName;
   }

   public function getAccountName()
   {
       return $this->accountName;
   }

   public function getAccountNumber()
   {
       return $this->accountNumber;
   }

}

        $myObj = new bankAccount('246810', 'Morgan Freeman');

        $serialized = serialize ($myObj);

        echo 'Object is serialized<br>';

        $newObj = unserialize ($serialized);

        echo 'Object is unserialized<br>';

        print_r ($newObj);
?>

In the above example the object is serialized, then unserialized to a new object variable. We then use the print_r() function to verify the new object contains everything the old one did resulting in the following output:

Object is serialized
Object is unserialized
bankAccount Object ( [accountNumber:private] => 246810 [accountname:private] => Morgan Freeman )

Once we have the serialized data in our $serialized we can do anything we want with it, such as write it to a file or send it through a network socket to another process where it can be unserialized and used.

Getting Information about a PHP Object

There are number of ways to find out information about classes.

An array of classes to which your script has access can be obtained using the get_declared_classes() function. The class_exists() function can be passed the name of a class to find out if such a class exists. A list of methods in a class can be obtained by passing the class name through to the get_class_methods() function.

It is also possible to find out if a class has a parent class using the get_parent_class() function which will either return the name of the parent class, or an empty string if no parent exists.

The method_exists() function, when passed an object pointer and method name as arguments, will return a true or false value indicating the existence of the method.