VB .Net Programming
Unit-IV:
Object Oriented Programming: Classes & objects,
Fields properties Methods & Events,
Constructor, inheritance.
Access Specifiers: Public, Private, Protected.
Overloading,
My Base & My class keywords.
Overview of OLE.
Object Oriented Programming: Classes & objects,
When you define a class, you define a blueprint for a data type. This doesn't actually define any data, but it does define what the class name means, that is, what an object of the class will consist of and what operations can be performed on such an object.
Objects are instances of a class. The methods and variables that constitute a class are called members of the class.
Class Definition
A class definition starts with the keyword Class followed by the class name; and the class body, ended by the End Class statement. Following is the general form of a class definition −
[ <attributelist> ] [ accessmodifier ] [ Shadows ] [ MustInherit | NotInheritable ] [ Partial ] _ Class name [ ( Of typelist ) ]
[ Inherits classname ]
[ Implements interfacenames ]
[ statements ]
End Class
Where,
∙ attributelist is a list of attributes that apply to the class. Optional.
∙ accessmodifier defines the access levels of the class, it has values as - Public, Protected, Friend, Protected Friend and Private. Optional.
∙ Shadows indicate that the variable re-declares and hides an identically named element, or set of overloaded elements, in a base class. Optional.
∙ MustInherit specifies that the class can be used only as a base class and that you cannot create an object directly from it, i.e., an abstract class. Optional. ∙ NotInheritable specifies that the class cannot be used as a base class. ∙ Partial indicates a partial definition of the class.
∙ Inherits specifies the base class it is inheriting from.
∙ Implements specifies the interfaces the class is inheriting from.
Module mybox
Class Box
Public length As Double ' Length of a box
Public breadth As Double ' Breadth of a box
Public height As Double ' Height of a box
End Class
Sub Main()
Dim Box1 As Box = New Box() ' Declare Box1 of type Box
Dim Box2 As Box = New Box() ' Declare Box2 of type Box
Dim volume As Double = 0.0 ' Store the volume of a box here
' box 1 specification
Box1.height = 5.0
Box1.length = 6.0
Box1.breadth = 7.0
' box 2 specification
Box2.height = 10.0
Box2.length = 12.0
Box2.breadth = 13.0
'volume of box 1
volume = Box1.height * Box1.length * Box1.breadth
Console.WriteLine("Volume of Box1 : {0}", volume)
'volume of box 2
volume = Box2.height * Box2.length * Box2.breadth
Console.WriteLine("Volume of Box2 : {0}", volume)
Console.ReadKey()
End Sub
End Module
Fields properties Methods & Events,
Fields like this can give you direct access to the data stored inside an object, and that's unusual in OOP because you usually want to check the data being stored in your objects to make sure it's legal first. An easy way of guarding access to the data in your objects is to use properties. We're all familiar with properties of objects.
TextBox1.Size = New Size(150, 20)
TextBox1.Location = New Point(80, 20)
TextBox1.Text = "Hello from Visual Basic"
Methods
A method is an action that an object can perform. For example, Add is a method of the ComboBox object, because it adds a new entry to a combo box.
The following procedure uses the Add method to add a new item to a ComboBox.
Sub AddEntry(newEntry as String)
Combo1.Add newEntry
End Sub
Properties
A property is an attribute of an object that defines one of the object's characteristics, such as size, color, or screen location, or an aspect of its behavior, such as whether it is enabled or visible. To change the characteristics of an object, you change the values of its properties.
To set the value of a property, follow the reference to an object with a period, the property name, an equal sign (=), and the new property value. For example, the following procedure changes the caption of a Visual Basic form by setting the Caption property.
Sub ChangeName(newTitle)
myForm.Caption = newTitle
End Sub
You can't set some properties. The Help topic for each property indicates whether you can set that property (read-write), only read the property (read-only), or only write the property (write-only).
You can retrieve information about an object by returning the value of one of its properties. The following procedure uses a message box to display the title that appears at the top of the currently active form.
Sub GetFormName()
formName = Screen.ActiveForm.Caption
MsgBox formName
End Sub
Events
An event is an action recognized by an object, such as clicking the mouse or pressing a key, and for which you can write code to respond. Events can occur as a result of a user action or program code, or they can be triggered by the system.
Constructors and Destructors in VB.NET
Constructors used in a class are member functions to initialize or set the objects of a class in VB.net. They dont return any value and are defined in a Sub with a keyword New. Multiple constructors can be created in class with any access specifiers, by default constructors are of Public access type.
Example:
Module Module1
Public Class Sample
Private a As Integer
Public Sub New(ByVal setval As Integer)
a = setval
End Sub
Public Function disp()
Return a
End Function
End Class
Sub Main()
Dim d As New Sample(5)
Console.WriteLine("Value of a is initialized to:")
Console.WriteLine(d.disp())
Console.Read()
End Sub
End Module
Result:
Value of a is initialized to:
5
Description:
In the above example, using the Constructor declared within the sub procedure New the value of a is set to 5.
Destructors:
Destructors or finalizer is a method used to deallocate the resources of an object that are no longer used, its invoked automatically by the VB.net environment. The keyword Overrides is used with the Finalizer method.
Example:
Protected Overrides Sub Finalize()
Console.WriteLine("Calling Destructor")
Ens Sub
INHERITANCE:
It is a primary feature of Object-Oriented Programming,
Inheritance is an element of Object-Oriented Programming by which we can derive the members of one class the "base class" for another class the "child class". When we derive a class from a base class, the derived class will inherit all members of the base class except constructors. With the help of inheritance we can create an object that can reuse code. Once a method is defined in a super class, it is automatically inherited by all subclasses, they share a common set of properties. Object-Oriented Programming allows classes to inherit commonly used state and behaviour from other classes. By using inheritance we can reduce the testing and developing efforts. The behaviour of the base class can be changed by writing code in the derived class. This technique is called overriding. With the new implementations of the derived class the inherited methods can also be override. Inheritance allows you to build a hierarchy of related classes and to reuse functionality defined in existing classes. All classes created with Visual Basic are inheritable by default. In Visual Basic we use the Inherits keyword to inherit one class from another.
This code shows how to declare the inherit class:
Public Class Base
End Class
Public Class Derived
Inherits Base
'Derived class inherits the Base class
End Class
Derived classes inherit, and can extend the methods, properties and events of the base class. With the use of inheritance we can use the variables, methods, properties, events etc, from the base class and add more functionality to it in the derived class.
Imports System. Console
Module Module1
Sub Main()
Dim Obj As New Subclass()
WriteLine(Obj.sum())
Read()
End Sub
End Module
Public Class Superclass
'base class
Public X As Integer = 5
Public Y As Integer = 15
Public Function add() As Integer
Return X + Y
End Function
End Class
Public Class Subclass
Inherits Base
'derived class.Class Subclass inherited from class Superclass
Public Z As Integer = 25
Public Function sum() As Integer
'using the variables, function from superclass and adding more functionality Return X + Y + Z
End Function
End Class
VB.NET Access Specifiers
AccessSpecifiers describes as the scope of accessibility of an Object and its members. We can control the scope of the member object of a class using access specifiers. We are using access specifiers for providing security of our applications.
Visual Basic .Net provide five access specifiers , they are as follows :
▪ Public
▪ Private
▪ Protected
▪ Friend
▪ ProtectedFriend
Public :
Public is the most common access specifier. It can be access from anywhere, hat means there is no restriction on accessability. The scope of the accessibility is inside class also in outside the class.
Public Class Book
Public Title As String
End Class
Public Class BookUser
Public Sub SomeMethod()
Dim x as new Book()
x.Title="VB.NET Programming"
End Sub
End Class
Private :
The scope of the accessibility is limited only inside the classes in which they are decleared. The Private members can not be accessed outside the class and it is the least permissive access level.
Public Class Book
Private strTitle As String
Public Property Title()
Get
Return strTitle
End Get
Set(ByVal Value)
strTitle = Value
End Set
End Property
End Class
Protected :
The scope of accessibility is limited within the class and the classses derived (Inherited )from this class.
Public Class Class1
Protected age As Integer
'... other code
End Class
Public Class Class2
Inherits Class1
Public Sub SomeMethod()
age = 99 'OK
End Sub
End Class
Public Class Class3
Public Sub SomeMethod()
Dim x As New Class1()
x.age = 99 'ERROR
End Sub
End Class
Friend :
The Friend access specifier can access within the program that contain its declarations and also access within the same assembly level. You can use friend instead of Dim keyword.
Public Class Class1
Friend age As Integer
'... other code
End Class
Public Class Class2
Public Sub SomeMethod()
Dim x As New Class1()
x.age = 99 'OK
End Sub
End Class
ProtectedFriend :
ProtectedFriend is same access lebels of both Protected and Friend. It can access anywhere in the same assebly and in the same class also the classes inherited from the same class .
Overloading in VB.NET
Overloading in visual basic.net is the method by which a property or a method takes different forms at different instances. It can also be termed as "Polymorphism".
Example:
Module Module1
Public Class mul
Public a, b As Integer
Public c, d As Double
Public Function mul(ByVal a As Integer) As Integer
Return a
End Function
Public Function mul(ByVal a As Integer,
ByVal b As Integer) As Integer
Return a * b
End Function
Public Function mul(ByVal d As Double,
ByVal c As Double) As Double
Return d * c
End Function
End Class
Sub Main()
Dim res As New mul
System.Console.WriteLine
("Overloaded Values of Class Mul is::")
System.Console.WriteLine(res.mul(10))
System.Console.WriteLine(res.mul(20, 10))
System.Console.WriteLine(res.mul(12.12, 13.23))
Console.Read()
End Sub End Module
Result:
Overloaded values of Class Mul is:
10
200
160.3476
MyBase
The MyBase keyword behaves like an object variable that refers to the base class of the current instance of a class.
Public Class Person
Public Sub DoSomething()
Console.WriteLine("Person")
End Sub
End Class
Public Class Customer
Inherits Person
Public Sub DoSomethingElse()
MyBase.DoSomething()
End Sub
End Class
Usage example:
Dim p As New Person
p.DoSomething()
Console.WriteLine(" --- ")
Dim c As New Customer
c.DoSomething()
c.DoSomethingElse()
Output:
Person
Person
Person
Me uses the current object instance.
MyClass
uses the member definition in the class where the member is called
Class Person
Public Overridable Sub DoSomething()
Console.WriteLine("Person")
End Sub
Public Sub useMe()
Me.DoSomething()
End Sub
Public Sub useMyClass()
MyClass.DoSomething()
End Sub
End Class
Class Customer
Inherits Person
Public Overrides Sub DoSomething()
Console.WriteLine("Customer")
End Sub
End Class
Example Usage:
Dim c As New Customer
c.useMe()
c.useMyClass()
Output:
Customer
Person
Overview of OLE
What is OLE?
OLE (Object Linking and Embedding) is a means to interchange data between applications. Of late OLE has been enhanced to provide not just data but also methods that can be used by client application.
Before we proceed any further, let us understand a few terms related to OLE.
OLE Server
This is an application that can provide objects to other applications. This is also called as OLE Source application.
OLE Client
This is an application that uses objects provided by OLE Server. This is also called as OLE Container as it contains objects provided by OLE Server.
Not every application is an OLE Server. Only a few applications are capable of providing objects. In the same way not all applications are capable of receiving objects. However, there are applications, such as MS-Word and MS-Excel that are capable of being OLE source as well as OLE Container.
What is Object Embedding?
In object embedding, an object is embedded in the client application. Along with the object, client application also stores the information regarding source application (or server) that created the object. The data stored in client application is separate and no link is maintained between the data supplied by source application and data stored in client application.
The advantage with Object Embedding is, client application maintains its own copy of the data.
The disadvantage is, changes made to original data (in source application) will not be incorporated in the data maintained by client.
Whenever you double click on the object in container application, the source application will be invoked (as information regarding source application is maintained) and the data of client application is placed in source application for editing.
1. A collection of cells from a spreadsheet of MS-Excel is copied to clipboard. As MS-Excel is an OLE Server, it copies the data in the form of an object.
2. Paste the data (now in the form of an object) from Clipboard to a document in Ms-Word. 3. Now the data is embedded into MS-World document as an object. Ms-Word document contains its own copy of the data.
4. If you double click on the object in MS-Word, then an instance of MS-Excel is invoked and data from MS-Word is copied into MS-Excel.
5. User can edit embedded data using MS-Excel.
6. If user saves changes and exits MS-Excel then modified data is placed in MS-Word document.
What is Object Linking?
Object linking makes changes made to source application available to container application. This is because container doesn’t store a separate copy of the data, instead it maintains a link to data in source application.
If you take the same example as previous one, in object linking, no separate copy of the required portion of spreadsheet is stored in MS-Word document, instead, the name of the file and the location of the data in the file are only maintained. Whenever you open MS-Word document, the data is taken from the spreadsheet file from where the data for object is taken. That is the reason why changes made in spreadsheet file (source) will be available to container application.
Advantages of Object Linking are:
• Changes made in source document are available to clients.
• As no separate copy of data is stored in clients, it saves space on disk. Disadvantage of Object Linking is:
• If original data is lost, then client Application cannot access data.
The End
No comments:
Post a Comment