Gui Unit 4

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

UNIT 4 – Object Oriented Programming with VB.

NET

Object-oriented programming (OOP) is a programming paradigm based on the concept of


"objects", which may contain data, in the form of fields, often known as attributes; and code, in
the form of procedures, often known as methods. A feature of objects is that an object's
procedures can access and often modify the data fields of the object with which they are
associated. VB.NET is completely object oriented.

The four basics concept of OOP are :


1. Abstraction
2. Encapsulation
3. Inheritance
4. polymorphism.

Advantages of OOPS over procedural oriented programming:


1) OOPs makes development and maintenance easier where as in Procedure-oriented
programming language it is not easy to manage if code grows as project size grows.

2) OOPs provides data hiding whereas in Procedure-oriented programming language a global


data can be accessed from anywhere.

3) OOPs provides ability to simulate real-world event much more effectively. We can provide
the solution of real word problem if we are using the Object-Oriented Programming language.

Class
A Class is a definition of a real life object. The terms class and object are sometimes used
interchangeably, but in fact, classes describe the type of objects, while objects are
usable instances of classes. So, the act of creating an object is called instantiation. Using the
blueprint analogy, a class is a blueprint, and an object is a building made from that blueprint. A
Class consists of data members and member functions that operate on these data members. A
class definition starts with the keyword Class followed by the class name; and the class body,
ended by the End Class statement. For example,
Public Class Car
Public MaximumSpeed as Integer
Public ModelName as String
Public Sub Accelerate()
'Some code to make the car go
End Sub
End Class

Object
An object is an instance of a Class. The methods and variables that constitute a class are called
members of the class. Members of a class can be access by using the name of the object with dot
operators. In order to access the above class, declare a variable of that class as follows:
Dim c as car
Then using dot operator, you can access the variables and function to that class:
c.MaximumSpeed=200
c.ModelName= “Ferrari”

GUI PROGRAMMING: Govt. Zirtiri Residential Science College Page 1


c.Accelerate()

Steps to create a class


1. On the Project menu, click Add Class.
2. Type the following code:
Class Example
Private _value As Integer
Public Sub New()
_value = 2
End Sub
Public Function Value() As Integer
Return _value * 2
End Function
End Class
Module Module1
Sub Main()
Dim x As Example = New Example()
Console.WriteLine(x.Value())
End Sub
End Module

Output

Methods
A method is an action that an object can perform. A method is just a block of code that you can
call from your program. Methods are used to access or manipulate the characteristics of an object
or a variable. There are mainly two categories of methods you will use in your classes:
(i) If you are using a control such as one of those provided by the Toolbox, you can call any
of its public methods. The requirements of such a method depend on the class being used.
Some of the common methods are show(), hide(), refresh(),focus(), copy(), paste() etc.
(ii) If none of the existing methods can perform your desired task, you can add a method to a
class by creating sub or function statement: the Sub statement is used if the method does
not return a value; the Function statement is used if a method returns a value.
To define a method of a class:

Class SampleClass
Public Sub Sampleproc
' Add code here
End Sub

Public Function SampleFunc(ByVal SampleParam As String)


' Add code here
End Function
End Class

GUI PROGRAMMING: Govt. Zirtiri Residential Science College Page 2


Properties
Properties represent information that an object contains. 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. You can change the property of a given
control during design time and runtime (coding). To set the value of a property during runtime,
type the name of the control or object, followed by a period(.), the property name, an equal sign
( = ), and the new property value. For example, the following procedure changes the property of
a label:
Label1.text=”Welcome to VB.NET”
Label1.forecolor=vb.red
Label1.backcolor=vb.gray
Label1.textalign=middlecentre

Inheritance
Inheritance is an object oriented concept in which one class, called a subclass, can be based on
another class, called a base class. Inheritance provides a mechanism for creating hierarchies of
objects. Inheritance is the property in which, a derived class acquires the attributes of its base
class. In simple terms, you can create or 'inherit' your own class (derived class), using an existing
class (base class).
For example, a programmer is a human being and Tom is a programmer. Thus the programmer
class inherits the properties and methods of the human class, and the Tom class inherits from
both programmer and human.
You can use the Inherits keyword for this.
Let us see a simple example. Import the System namespace.

Imports System
Our simple base class:

Class Human
Public Sub Walk()
Console.Writeline ("Walking")
End Sub
End Class
Now, let us derive a class from Human.
A Programmer is a Human.

Class Programmer
Inherits Human
Public Sub StealCode()
Console.Writeline ("Stealing code")
End Sub
End Class
Just a MainClass.

Class MainClass

GUI PROGRAMMING: Govt. Zirtiri Residential Science College Page 3


Shared Sub Main()
Dim Tom as Programmer
Tom=new Programmer

Tom.Walk()
Tom.StealCode()
End Sub
End Class

Encapsulation
The wrapping up of data and operations / functions (that operate on the data) into a single unit
(called class) is known as Encapsulation. Encapsulation is implemented with the help of a class
as a class binds together data and its associated function under one unit.
Encapsulation is the exposure of properties and methods of an object while hiding the actual
implementation from the outside world. In other words, the object is treated as a black box—
developers who use the object should have no need to understand how it actually works.
Encapsulation allows developers to build objects that can be changed without affecting the client
code that uses them. The key is that the interface of the object, the set of exposed properties and
methods of the object, doesn't change even if the internal implementation does. VB has
supported encapsulation since version 4.0.
Eg. Private textbox1 as new textbox
Textbox1.text=”Hello”
Textbox1.clear()
textbox1.refresh()
In the above example, the property and method of textbox is accessible without knowing the
implementation of its methods.

Data Hiding or Abstraction:


Abstraction refers to the act of representing essential features without including the background
details or explanations. For example, engine details of a car are hidden from the driver which are
abstracted from the driver. Normally, in a Class, variables used to hold data (like the age of a
dog) is declared as Private. Functions or property routines are used to access these variables.
Protecting the data of an object from outside functions is called Abstraction or Data Hiding. This
prevents accidental modification of data by functions outside the class.

Overloading
Overloading refers to an item being used in more than one way. Operator names are often
overloaded. For instance, the plus sign (+) refers to addition of integers, addition of singles,
addition of doubles, and concatenation of strings. Thus, the plus symbol (+) is overloaded. It’s a
good thing, too; otherwise, we would need separate symbols for adding integers, singles, and
doubles.
Function names can also be overloaded. For instance, the absolute value function, Abs, can take
an integer parameter, a single parameter, or a double parameter. Because the name Abs
represents several different functions, it is overloaded. In fact, if you look at the documentation
for the Abs member of the Math class (in the System namespace of the Framework Class
Library), you will find the following declarations, showing the different functions using the Abs
name:

GUI PROGRAMMING: Govt. Zirtiri Residential Science College Page 4


Overloads Public Shared Function Abs(Decimal) As Decimal
Overloads Public Shared Function Abs(Double) As Double
Overloads Public Shared Function Abs(Integer) As Short
Overloads Public Shared Function Abs(Integer) As Integer
Overloads Public Shared Function Abs(Long) As Long
Overloads Public Shared Function Abs(SByte) As SByte
Overloads Public Shared Function Abs(Single) As Single

Note the use of the Overloads keyword, which tells VB that this function is overloaded.
Specifically, a function name is overloaded when two defined functions use the same name but
have different argument signatures. For instance, consider a function that retrieves a current
account balance. The account could be identified either by the person’s name or by the account
number. Thus, we might define two functions, each called GetBalance:

Overloads Function GetBalance(sCustName As String) As Decimal


Overloads Function GetBalance(sAccountNumber As Long) As Decimal

Note also that VB.NET permits function overloading only because the argument signatures of
the two functions are different, so that no ambiguity can arise. The function calls:

GetBalance("John Smith")
GetBalance(123456)

are resolved by the compiler without difficulty, based on the data type of the argument. This type
of overloading is often referred to as overloading the function GetBalance. On the other hand,
there are two different functions here, so it seems more appropriate to say that the
function name is being overloaded. Overloading is very common and not exclusive to object-
oriented programming.

Overriding
By default, a derived class Inherits methods from its base class. If an inherited property or
method needs to behave differently in the derived class it can be overridden; that is, you can
define a new implementation of the method in the derived class. The Overridable keyword is
used to mark a function as overridable. The keyword Overrides is used to mark that a function
is overriding some base class function. Let us see an example.
Import the System namespace.
Imports System
Our simple base class:
Class Human
Overridable Public Sub Speak()
Console.Writeline ("Speaking")
End Sub
End Class
Now, let us derive a class from Human:
An Indian is a Human:
Class Indian
GUI PROGRAMMING: Govt. Zirtiri Residential Science College Page 5
Inherits Human
Overrides Public Sub Speak()
Console.Writeline ("Speaking Hindi")
End Sub
End Class
Just a class to put our Main().
Class MainClass
Shared Sub Main()
Dim Tom as Human
Tom=new Human
Dim Tony as Indian
Tony=new Indian
Tom.Speak()
Tony.Speak()
End Sub
End Class

Polymorphism
Polymorphism is the property in which a single object can take more than one form. For
example, if you have a base class named Human, an object of Human type can be used to hold an
object of any of its derived type. When you call a function in your object, the system will
automatically determine the type of the object to call the appropriate function. For example, let
us assume that you have a function named speak() in your base class. You derived a child class
from your base class and overloaded the function speak(). Then, you create a child class object
and assign it to a base class variable. Now, if you call the speak() function using the base class
variable, the speak() function defined in your child class will work. On the contrary, if you are
assigning an object of the base class to the base class variable, then the speak() function in the
base class will work. This is achieved through runtime type identification of objects. See the
example.
Import the System namespace.
Imports System
This example is exactly the same as the one we saw in the previous lesson. The only difference is
in the Shared Sub Main() in the class MainClass. So scroll down and see an example:
Our simple base class:
Class Human
Overridable Public Sub Speak()
Console.Writeline ("Speaking")
End Sub
End Class
Now, let us derive a class from Human.
An Indian is a Human.
Class Indian
Inherits Human
Overrides Public Sub Speak()
Console.Writeline ("Speaking Hindi")

GUI PROGRAMMING: Govt. Zirtiri Residential Science College Page 6


End Sub
End Class
Carefully examine the code in Main():
Class MainClass
Shared Sub Main()
Dim Tom as Human
Tom=new Indian
Tom.Speak()
End Sub
End Class

Constructors
A Constructor is a special function which is called automatically when a class is created.
Constructors usually initialize the data members of the new object. A constructor can run only
once when a class is created. Furthermore, the code in the constructor always runs before any
other code in a class. However, you can create multiple constructor overloads in the same way as
for any other method.
In VB.NET, you should use New() to create constructors. Constructors can be overloaded but
unlike the functions, the Overloads keyword is not required.

Class Dog
Private Age as integer
The default constructor:
Public Sub New()
Console.Writeline ("Dog is Created With Age Zero")
Age=0
End Sub
The parameterized constructor:
Public Sub New(val as Integer)
Console.Writeline ("Dog is Created With Age " + Convert.ToString(val))
Age=val
End Sub

Destructors
Destructors are used to destruct instances of classes. A Destructor is a special function which is
called automatically when a class is destroyed. In VB.NET, you should use Finalize() routine
to create Destructors. In the .NET Framework, the garbage collector automatically manages the
allocation and release of memory for the managed objects in your application. However, you
may still need destructors to clean up any unmanaged resources that your application creates.
There can be only one destructor for a class. For example,
Overrides Protected Sub Finalize()
Console.Writeline ("Dog is Destroyed")
End Sub
Shared Sub Main()

GUI PROGRAMMING: Govt. Zirtiri Residential Science College Page 7


Dim Jimmy, Jacky as Dog
Jimmy=new Dog
Jacky=new Dog(10)
End Sub
End Class

Interfaces
Interfaces define only the properties, methods, and events that classes can implement without
defining the actual code. A class or struct that implements the interface must implement the
members of the interface. There are several other reasons why you might want to use interfaces
instead of class inheritance:
(i) Interfaces are better suited to situations in which your applications require many possibly
unrelated object types to provide certain functionality.
(ii) Interfaces are more flexible than base classes because you can define a single
implementation that can implement multiple interfaces.
(iii) Interfaces are better in situations in which you do not have to inherit implementation from
a base class.
(iv) Interfaces are useful when you cannot use class inheritance. For example, structures
cannot inherit from classes, but they can implement interfaces.

Interface Interface1
Sub sub1(ByVal i As Integer)
End Interface
Interface Interface2 Inherits Interface1
Sub M1(ByVal y As Integer)
ReadOnly Property Num() As Integer
End Interface
Public Class MyClass Implements Interface1
Sub Sub1(ByVal i As Integer) Implements Interface1.sub1
' Insert code here to implement this method.
End Sub
End Class

Access Modifier
Access modifiers are keywords in object oriented languages that set the accessibility of classes,
methods, and other members. VB.NET offers levels of accessibility, as follows:
• Public. Public class members don't have access restrictions. You use the
keyword Public in front of the class member to make it available publicly. For example,
if the method in the class is a public method. It can be called from anywhere.
Eg. Public sub add()
The sub procedure add() can be access anywhere inside the project.
• Private. Private class member can only be accessed from inside the class itself. Use
the Private keyword to make a class member private
Eg. Private rollno as integer
The variable rollno is accessible only within the procedure
• Protected. A protected member is accessible to a derived class and from inside the class
itself. Use the Protected keyword to make a member protected.
GUI PROGRAMMING: Govt. Zirtiri Residential Science College Page 8
Eg. Protected sub insert()
The sub procedure insert() can be access from the derived class and the class itself.
• Friend. Members with the friend access restriction are accessible only within the
program that contains the class declaration. Use the keyword Friend to make a member
have friend restriction.
Eg. Friend sub update()
The sub procedure update() can be access from the friend class and the class itself.

Namespace
In VB.NET, classes and other data structures for a specific purpose are grouped together to form
a namespace. You can use the classes in a namespace, by simply importing the namespace.
The Imports keyword is used to import a namespace to your project. .NET framework provides
a rich set of built in classes, grouped together to various namespaces.
You can create namespace by using the keyword Namespace followed by the name of the
namespace. It must end with End Namespace.
Namespace MyNamespace
'code here
End Namespace

Import keyword
The Imports keyword is used to import a namespace to your project. The .NET framework
provides a rich set of built in classes, grouped together to various namespaces.
Syntax
Imports [ aliasname = ] namespace
-or-
Imports [ aliasname = ] namespace.element

Parts
Term Definition

aliasname Optional. An import aliasor name by which code can refer


to namespace instead of the full qualification string.

namespace Required. The fully qualified name of the namespace being


imported. Can be a string of namespaces nested to any level.

element Optional. The name of a programming element declared in the


namespace. Can be any container element.

For example,
Imports System
Imports System.data.oledb

GUI PROGRAMMING: Govt. Zirtiri Residential Science College Page 9


CREATING CLASS LIBRARY IN VISUAL STUDIO 2010.
The step by step method for creating class library in visual studio 2010 is given below:
(1) Open or start Visual Studio 2010.
(2) On the File menu, select New Project to open the New Project dialog box.
(3) In the list of Windows project types, select Class Library, and then type filename and then
click OK.
(4) Class1.vb will be created in the Solution Explorer. Right-Click on that file and select View
Code.
(5) Write all the necessary Class Library codes there.
(6) Click Debug button to compile and debug your code. If you successfully debug, DLL file
will be created in the output Debug or Release folder. You can use that DLL Class Library
file to wherever project you want.
(7) To use the DLL into your project, right-click on Project name and then select Add
Reference…
(8) Locate and select the DLL file you previously created.
(9) On the top of the code, import the class Library and by using Imports file.dll.
(10) Now, you can use the different functions or methods available in your class Library.

GUI PROGRAMMING: Govt. Zirtiri Residential Science College Page 10

You might also like