Unit 4

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 62

UNIT 4


OBJECT ORIENTED PROGRAMMING
WITH VB.NET
Object Oriented
Programming

 VB.NET is a simple, multi-paradigm object-oriented
programming language designed to create a wide
range of Windows, Web, and mobile applications
built on the .NET Framework.
 Object-oriented programming (OOP) is 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.

The four basics concept of OOP are :
Abstraction
Encapsulation
Inheritance
polymorphism.
Advantages of OOP

Modularity:
Inheritance:
Encapsulation:
Flexibility and Scalability:
Code Organization:
Code Maintenance:
Code Reusability:
Better Problem Solving:
Disadvantages of OOP

Steeper learning curve:
Increased complexity:
Performance overhead:
Dependency management:
Overuse of inheritance:
Class

A Class is a definition of a real life object.
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.

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.
Members of a class can be access by using the
name of the object with dot operators. Eg
Dim c as car
Then using dot operator, you can access the
variables and function to that class:
c.MaximumSpeed=200
c.ModelName= “Ferrari”
c.Accelerate()
Sytax of Class Declaration


[ Access_Specifier ] [ Shadows ] [ MustInherit | NotInheritable]
[ Partial ] Class ClassName
' Data Members or Variable Declaration
' Methods Name
' Statement to be executed
End Class
Class Box Box2.height = 10.0
Public length As Double Box2.length = 12.0
Public breadth As Double Box2.breadth = 13.0
Public height As Double 'volume of box 1
End Class  volume = Box1.height *
Box1.length * Box1.breadth
Sub Main() Console.WriteLine("Volume of
Dim Box1 As Box = New Box() Box1 : {0}", volume)
'volume of box 2
Dim Box2 As Box = New Box() volume = Box2.height *
Dim volume As Double = 0.0 Box2.length * Box2.breadth
Console.WriteLine("Volume of
' box 1 specification Box2 : {0}", volume)
Box1.height = 5.0 Console.ReadKey()
Box1.length = 6.0 End Sub
Box1.breadth = 7.0
' box 2 specification

Output

Volume of Box1 : 210


Volume of Box2 : 1560
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.
Some of the common methods are show(),
hide(), refresh(),focus(), copy(), paste() etc.
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.
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
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).

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.
 You can use the Inherits keyword for this.


Imports System Public Shared Sub
Class Human Main(ByVal args As String())
Public Sub Walk() Dim Tom As Programmer

Console.Writeline("Walking")
Tom = New Programmer

End Sub Tom.Walk()


End Class Tom.StealCode()
Class Programmer Console.ReadLine()
Inherits Human End Sub
Public Sub StealCode() End Class

Console.WriteLine("Stealing
code")
End Sub
End Class
Output

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 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.

Module Module1
Class User
Public location As String
Public name As String


Public function Letsprint() as string
Return “Inside class function”
End Function
End Class

Sub Main()
Dim u As User = New User()
u.name = "Lalramliana"
u.location = "Venglai"
Console.WriteLine("Name: " & u.name)
Console.WriteLine("Location: " & u.Ulocation)
Console.WriteLine(Letsprint)
Console.WriteLine(vbLf & "Press Enter Key to Exit..")
Console.ReadLine()
End Sub
End Module
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.
 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.
Module Module1 Console.WriteLine("Brand: " &
Public Class Laptop Lbrand)
Private brand As String Console.WriteLine("Model: " &
Private model As String Lmodel)
End Sub


Public Property Lbrand() As String
Get Private Sub MotherBoardInfo()
Return brand Console.WriteLine("MotheBoard
Information")
End Get
End Sub
Set(ByVal value As String)
End Class
brand = value
Sub Main()
End Set
Dim l As Laptop = New Laptop()
End Property
l.Lbrand = "Dell"
Public Property Lmodel() As String
l.Lmodel = "Inspiron 14R"
Get
l.LaptopDetails()
Return model
Console.WriteLine("Press Enter Key to
End Get
Exit..")
Set(ByVal value As String)
Console.ReadLine()
model = value
End Sub
End Set
End Module
End Property
Public Sub LaptopDetails()
Output

Overloading

 Overloading refers to an item being used in more than
one way.
 Method Overloading means defining multiple
methods with the same name but with different
parameters.
 In visual basic, the Method Overloading is also called
as compile time polymorphism or early binding.
Module Module1
Public Class Calculate
Public Sub AddNumbers(ByVal a As Integer, ByVal b As Integer)


Console.WriteLine("a + b = {0}", a + b)
End Sub
Public Sub AddNumbers(ByVal a As Integer, ByVal b As Integer, ByVal c
As Integer)
Console.WriteLine("a + b + c = {0}", a + b + c)
End Sub
End Class
Sub Main(ByVal args As String())
Dim c As Calculate = New Calculate()
c.AddNumbers(1, 2)
c.AddNumbers(1, 2, 3)
Console.WriteLine("Press Enter Key to Exit..")
Console.ReadLine()
End Sub
End Module
Output

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.
Module Module1
Public Class BClass
Public Overridable Sub GetInfo()

End Sub
End Class

Console.WriteLine("Learn Vb.NET Tutorial")

Public Class DClass


Inherits BClass
Public Overrides Sub GetInfo()
Console.WriteLine("Welcome to Tutorial Point")
End Sub
End Class
Sub Main(ByVal args As String())
Dim d As DClass = New DClass()
d.GetInfo()
Dim b As BClass = New BClass()
b.GetInfo()
Console.WriteLine("Press Enter Key to Exit..")
Console.ReadLine()
End Sub
End Module
Output

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.
Module module1 ByVal w As Double)
Public Class Shape Height = h
Public Overridable Function Width = w
CalculateArea() As Double End Sub
Return 0
End Function
End Class
 Public Overrides Function CalculateArea()
As Double
Return Height * Width
Public Class Circle End Function
Inherits Shape End Class
Public Property Radius As Double Public Sub Main()
Public Sub New(ByVal rad As Double) Dim shape As Shape = New Shape()
Radius = rad Dim circle As Shape = New Circle(3.0)
End Sub Dim rectangle As Shape = New
Public Overrides Function CalculateArea() Rectangle(3.0, 4.0)
As Double Console.WriteLine("The area of the shape is
Return (3.14) * Math.Pow(Radius, 2) " & shape.CalculateArea())
End Function Console.WriteLine("The area of the circle is
End Class " & circle.CalculateArea())
Public Class Rectangle Console.WriteLine("The area of the
rectangle is " & rectangle.CalculateArea())
Inherits Shape
Console.ReadLine()
Public Property Height As Double
End Sub
Public Property Width As Double
End Module
Public Sub New(ByVal h As Double,
Output

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.

Following is the syntax of creating a constructor in
visual basic programming language.
Public Class User
' Constructor
Public Sub New()
' Your Custom Code
End Sub
End Class
Module Module1
Class User
Public name, location As String
' Default Constructor
Public Sub New()
name = "Suresh Dasari"

location = "Hyderabad"
End Sub
End Class
Sub Main()
Dim user As User = New User()
Console.WriteLine(user.name)
Console.WriteLine(user.location)
Console.WriteLine("Press Enter Key to Exit..")
Console.ReadLine()
End Sub
End Module
Output

Module Module1
Class User
Public name, location As String
' Parameterized Constructor


Public Sub New(ByVal a As String, ByVal b As String)
name = a
location = b
End Sub
End Class
Sub Main()
' The constructor will be called automatically once the instance
of the class created
Dim user As User = New User("Suresh Dasari", "Hyderabad")
Console.WriteLine(user.name)
Console.WriteLine(user.location)
Console.WriteLine("Press Enter Key to Exit..")
Console.ReadLine()
End Sub
End Module
Output

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

Class User
' Destructor
Protected Overrides Sub Finalize()
' Your Code
End Sub
End Class
Module Module1
Class User
Public Sub New()
Console.WriteLine("An Instance of class created")
End Sub 
Protected Overrides Sub Finalize()
Console.WriteLine("An Instance of class destroyed")
End Sub
End Class
Sub Main()
Details()
GC.Collect()
Console.ReadLine()
End Sub
Public Sub Details()
Dim user As User = New User()
End Sub
End Module
Output

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.
reasons why you might want to use
interfaces instead of class inheritance:

 Interfaces are better suited to situations in which
your applications require many possibly unrelated
object types to provide certain functionality.
 Interfaces are more flexible than base classes because
you can define a single implementation that can
implement multiple interfaces.
 Interfaces are better in situations in which you do not
have to inherit implementation from a base class.
 Interfaces are useful when you cannot use class
inheritance.
Module Module1
Interface IUser
Sub GetDetails(ByVal x As String)
End Interface
Class User
Implements IUser 
Public Sub GetDetails(ByVal a As String) Implements IUser.GetDetails
Console.WriteLine("Name: {0}", a)
End Sub
End Class
Class User1
Implements IUser
Public Sub GetDetails(ByVal a As String) Implements IUser.GetDetails
Console.WriteLine("Location: {0}", a)
End Sub
End Class
Sub Main(ByVal args As String())
Dim u As IUser = New User()
u.GetDetails(“Lalremruata")
Dim u1 As IUser = New User1()
u1.GetDetails(“Leitan")
Console.WriteLine("Press Enter Key to Exit..")
Console.ReadLine()
End Sub
End Module
Output

Access Modifier

 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()

 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

 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.
Eg. Protected sub insert()
 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.
Class CustomerInfo
Private p_CustomerID As Integer
Public ReadOnly Property CustomerID() As Integer
Get


Return p_CustomerID
End Get
End Property
' Allow friend access to the empty constructor.
Friend Sub New()
End Sub
Public Sub New(ByVal customerID As Integer)
p_CustomerID = customerID
End Sub
' Allow friend programming elements to set the customer identifier.
Friend Sub SetCustomerID(ByVal customerID As Integer)
p_CustomerID = customerID
End Sub
End Class
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.

The Imports keyword is used to import a namespace to
your project.
Imports System.Drawing
Imports System.Windows.Media
Import System.Data.Oledb
Import System.Data.SqlClient

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
Imports System Module Module1
Namespace Birds Sub main()
Class Parrot Birds.Parrot.fly()
Public Shared Sub fly() Birds.Parrot.color()
Console.WriteLine("Parrot
can fly")
 Birds.Parrot.type()
Console.ReadLine()
End Sub End Sub
Public Shared Sub color() End Module
Console.WriteLine
("normally Parrots are green")
End Sub
Public Shared Sub type()
Console.WriteLine("Different
type of parrot are found around the
world")
End Sub
End Class
End Namespace
Output

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

Term Definition

aliasname Optional. An import alias or 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.
CREATING CLASS LIBRARY IN VISUAL
STUDIO 2010.


 Open or start Visual Studio 2010.
 On the File menu, select New Project to open the
New Project dialog box.
 In the list of Windows project types, select Class
Library, and then type filename and then click OK.
 Class1.vb will be created in the Solution Explorer.
Right-Click on that file and select View Code.
 Write all the necessary Class Library codes there.

 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.
 To use the DLL into your project, right-click on Project
name and then select Add Reference…
 Locate and select the DLL file you previously created.
 On the top of the code, import the class Library and by
using Imports file.dll.
 Now, you can use the different functions or methods
available in your class Library.

 END OF SLIDE

You might also like