Unit3
-
Upload
abha-damani -
Category
Technology
-
view
182 -
download
5
description
Transcript of Unit3
030010401 BCA 4th Semester
Preeti P Bhatt Department of Computer Science, UTU. 1 | P a g e
030010401- GUI Programming
Unit-2: Object Oriented Programming in Visual
Basic
BCA 4th Semester
Note: - This material is prepared by Ms. Preeti P Bhatt. The basic
objective of this material is to supplement teaching and discussion
in the classroom. Student is required to go for extra reading in the
subject through library work.
030010401 BCA 4th Semester
Preeti P Bhatt Department of Computer Science, UTU. 2 | P a g e
Topic Covered
Classes and objects: Fields, properties, shared and instance members, method overloading,
events, partial class, operator overloading and inner class
Constructors and destructors
Inheritance, Interface and Polymorphism: Deriving classes, calling base class constructor,
overriding Methods, non-inheritable classes, abstract class, interface inheritance
Collections: Array, ArrayList, Queue, traversing in collection
030010401 BCA 4th Semester
Preeti P Bhatt Department of Computer Science, UTU. 3 | P a g e
Class
To create a class, you only need to use the Class statement, which, like other compound
statements in Visual Basic, needs to end with End Class:
Public Class DataClass
⋮
End Class
This creates a new class named DataClass.
Object
You can create an object of this class, data, like this—note that you must use the New keyword
to create a new instance of a class:
Dim obj as new classname
Dim data As New DataClass()
You also can do this like this:
Dim data As DataClass = New DataClass()
Access Specifiers
Fields, Properties, Methods, and Events are called the members of a class. Inside the class,
members are declared as either Public, Private, Protected, Friend, or Protected Friend:
Public— Gives variables public access, which means there are no restrictions on their
accessibility.
Private— Gives variables private access, which means they are accessible only from
within their class, including any nested procedures.
Protected— Gives variables protected access, which means they are accessible only
from within their own class or from a class derived from that class. Note that you can
use Protected only at class level (which means you can't use it inside a procedure),
because you use it to declare members of a class.
Friend— Gives variables friend access, which means they are accessible from within the
program that contains their declaration, as well as anywhere else in the same assembly.
Protected Friend— Gives variables both protected and friend access, which means they
can be used by code in the same assembly, as well as by code in derived classes.
The fields of a class, also called the class's data members, are much like built-in variables
(although they also may be constants).
For example, I can declare a field named value to the DataClass class we just saw by declaring a
variable with that name:
030010401 BCA 4th Semester
Preeti P Bhatt Department of Computer Science, UTU. 4 | P a g e
Public Class DataClass
Public value As Integer
End Class
Now I can refer to that field in an object of this class using the familiar object.field syntax of
Visual Basic:
Dim data As New DataClass()
data.value = 5
You also can make fields hold constant values with Const:
Public Class Class1
Public Const Field1 As Integer = 0
⋮
End Class
Properties
Properties are what we refer to as ‘smart fields’, where a field is just another name for an
instance variable of a class.
Properties have get and set procedures, which provide more control on how values are set or
returned.
Syntax:
Private PropertyValue As String
Public Property Prop1() As String
Get
Return PropertyValue
End Get
Set(ByVal Value As String)
PropertyValue = Value
End Set
End Property
030010401 BCA 4th Semester
Preeti P Bhatt Department of Computer Science, UTU. 5 | P a g e
Creating Class (Shared) Data Members
You can use the Shared keyword to create class data members. You can use a class data member with the name of the class alone, no object needed.
For example, say you have a class named Mathematics, and declare a shared variable named Pi:
Public Class Mathematics
Public Shared Pi As Double = 3.1415926535
End Class
Now you can use Pi as a class variable with the Mathematics class directly, no object needed: integer5 = Mathematics.Pi
Shared Function
Private Sub Button1_Click(ByVal sender As System.Object,ByVal e As
System.EventArgs) Handles Button1.Click
txt3.Text = Mathematics.Add(txt1.Text,txt2.Text)
End Sub
Public Class Mathematics
Shared Function Add(ByVal x As Integer, ByVal y As Integer) As Integer
Return x + y
End Function
End Class
Events Syntax
[ <attrlist> ] [ Public | Private | Protected | Friend
|Protected Friend] [Shadows]
Event eventname[(arglist)]
[ Implements interfacename.interfaceeventname ]
eventname—Required. Name of the event. interfacename—The name of an interface. interfaceeventname—The name of the event being implemented.
Public Class Form1
Dim WithEvents tracker As New ClickTrack()
Private Sub tracker_ThreeClick(ByVal Message As String)
Handles tracker.ThreeClick
MsgBox(Message)
End Sub
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
030010401 BCA 4th Semester
Preeti P Bhatt Department of Computer Science, UTU. 6 | P a g e
tracker.Click()
End Sub
End Class
Public Class ClickTrack
Public Event ThreeClick(ByVal Message As String)
Public Sub Click()
Static ClickCount As Integer = 0
ClickCount += 1
If ClickCount >= 3 Then
ClickCount = 0
RaiseEvent ThreeClick("You clicked three times")
End If
End Sub
End Class
Partial Class
Definition: Partial Class allows splitting definition of classes, interfaces and structures over more than one file.
The compilers for VB.Net or C# look for the partial classes and integrate them while compiling, to form the intermediate language.
Benefits of partial class:
1. It allows programmers to work simultaneously on different parts of a class without needing to share the same physical file.
2. You can easily write your code for extended functionality for a VS.NET generated class. This will allow you to write the code of your own need without messing with the system generated code.
Example:
Public Class Calcuator
Dim a As New Integer
Dim b As New Integer
Dim Total As Integer
Public Sub ADD()
Total=a+b
End Sub
End Class
Partial Public Class Calcuator
030010401 BCA 4th Semester
Preeti P Bhatt Department of Computer Science, UTU. 7 | P a g e
Dim c As New Integer
Dim d As New Integer
Dim Mul As Integer
Public Sub MULT()
Mul=c*d
End Sub
End Class
Inner Class
Inner class is a class defined inside a class that can be used within the scope of the class in which it is defined. Syntax:
Public Class OuterClass
Private Class Interclass
‘Code of Interclass
End Class
‘Code of OuterClass
End Class
Example:
‘Code Written in Class File
Class outerclass
Public Sub outermethod()
MsgBox("Outer Method")
End Sub
Class innerclass
Public Sub innermethod()
MsgBox("Inner Method")
End Sub
End Class
End Class
‘Code Written in Form Class
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim obj As New outerclass
obj.outermethod()
Dim obj1 As New outerclass.innerclass
030010401 BCA 4th Semester
Preeti P Bhatt Department of Computer Science, UTU. 8 | P a g e
obj1.innermethod()
End Sub
End Class
Constructor
• A constructor is a special member function whose task is to initialize the objects of it's class.
• This is the first method that is run when an instance of a type is created.
• A constructor is invoked whenever an object of its associated class is created.
• If a class contains a constructor, then an object created by that class will be initialized automatically.
Syntax:
Default Constructor Public Sub New()
// initialization
End Sub
Parameterized Constructor Public Sub New(ByVal value As Integer)
// initialization
End Sub
Example
Class form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles Button1.Click
Dim s1 As New Test() ‘ Calling Default Constructor
Dim s2 As New Test(8)‘Calling Parameterized Constructor.
End Class
Class Test
Private a As Integer
'Default Constructor
Public Sub New()
a = 0
End Sub
'Parameterized Constructor
Public Sub New(ByVal f As Integer)
a = f
End Sub
End Class
030010401 BCA 4th Semester
Preeti P Bhatt Department of Computer Science, UTU. 9 | P a g e
Destructor
A destructor, also known as finalizer, is the last method run by a class.
Within a destructor we can place code to clean up the object after it is used, which might include decrementing counters or releasing resources.
We use Finalize method in Visual Basic for this and the Finalize method is called automatically when the .NET runtime determines that the object is no longer required.
When working with destructors we need to use the overrides keyword with Finalize method as we will override the Finalize method built into the Object class.
We normally use Finalize method to deallocate resources and inform other objects that the current object is going to be destroyed.
Because of the nondeterministic nature of garbage collection, it is very hard to determine when a class's destructor will be called.
Syntax:
Protected Overrides Sub Finalize ()
//Code
End Sub
Operator Overloading
When an operator can perform more than one operation with objects is called operator overloading. A function name can be replaced with the operator using operator keyword.
VB.NET allows the following operators to be overloaded:
+ (increment/plus - unary and binary)> - (decrement/minus - unary and binary)
\ (integer divide - binary) / (divide - binary)
Not (unary) * (multiply - binary)
& (concatenate - binary) Mod (binary)
And (binary) Or (binary)
<< (left shift - binary) >> (right shift - binary)
= (equals - binary) <> (not equals - binary)
< (less than - binary) > (greater than - binary)
<= (less than or equal to - binary) >= (greater than or equal to - binary)
030010401 BCA 4th Semester
Preeti P Bhatt Department of Computer Science, UTU. 10 | P a g e
Example:
Class form1
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
Dim s1 As New ClassOver(5)
Dim s2 As New ClassOver(8)
Dim s3 As Integer
MsgBox("Sum Using Operator Overload " & s3)
End Sub
End Class
Class ClassOver
Private a As Integer
Public Sub New(ByVal f As Integer)
a = f
End Sub
Public Shared Operator +(ByVal x As ClassOver, ByVal y As
ClassOver) As Integer
Dim f As Integer = x.a + y.a
Return f
End Operator
End Class
Inheritance
The process of deriving a new class from an existing class is called Inheritance.
A key feature of OOP is reusability. It's always time saving and useful if we can reuse something that already exists rather than trying to create the same thing again and again.
This is done by creating a new class from an existing class. The old class is called the base class and the new class is called derived class. The derived class inherits some or everything of the base class. In Visual Basic we use the Inherits keyword to inherit one class from other.
030010401 BCA 4th Semester
Preeti P Bhatt Department of Computer Science, UTU. 11 | P a g e
Syntax
Example:
Public Class One
---
---
End Class
Public Class Two
Inherits One
---
---
End Class
Element Context Description
Inherits Class Statement Indicates the class from which the new class inherits
NotInheritable Class Statement Indicates that a class that cannot be inherited by another class.
MustInherit Class Statement Indicates a class that must be inherited by another class
Public Class One 'base class
Protected i As Integer = 10
Protected j As Integer = 20
Public Function add() As Integer
Return i + j
End Function
End Class
Public Class Two
Inherits One 'derived class. class two inherited from class one
Public k As Integer = 100
Public Function sum() As Integer
Return k
End Function
End Class
Sub Main()
Dim ss As New Two()
Console.WriteLine(ss.add())
End Sub
030010401 BCA 4th Semester
Preeti P Bhatt Department of Computer Science, UTU. 12 | P a g e
Calling Base Class Constructor
We can call base class constructor using MyBase.New keyword. In derive class you should specified base class constructor parameter.
Example
Polymorphism Polymorphism means the ability to take more than one form.
Polymorphism is extensively used in implementing Inheritance. Polymorphism is the capability to have methods and properties in multiple classes
that have the same name and can be used interchangeably, even though each class implements the same properties or methods in different ways.
Module BaseclassConstructor
Sub Main()
Dim ss As New Two(5, 6, 7)
Console.WriteLine(ss.add())
Console.ReadKey()
End Sub
End Module
Public Class One 'base class
Protected i As Integer
Protected j As Integer
Sub New(ByVal a As Integer, ByVal b As Integer)
i = a
j = b
End Sub
Public Function add() As Integer
Return i + j
End Function
End Class
Public Class Two
Inherits One 'derived class. class two inherited from class one
Public k As Integer
Sub New(ByVal x As Integer, ByVal y As Integer, ByVal z As Integer)
MyBase.New(x, y)
k = z
End Sub
Public Function sum() As Integer
Return k
End Function
End Class
030010401 BCA 4th Semester
Preeti P Bhatt Department of Computer Science, UTU. 13 | P a g e
The following list will be use when you implementing polymorphism. o Overridable : Allows a property or method in a class to be overridden in a derived
class. o Overrides : Overrides an Overridable property or method defined in the base class. o NotOverridable : It prevents a property or method from being overridden in an
inheriting class. Public methods are NotOverridable by default.
o MustOverride : It requires that a derived class override the property or method. When the MustOverride keyword is used, the method definition consists of just
the Sub, Function, or Property statement. MustOverride methods must be declared in MustInherit classes.
o Shadowed : Shadow members are used to create a local version of a member that has broader scope. For example, you can declare a property that shadows an inherited method
with the same name.
Element Context Description
Overridable Procedure Indicates a procedure that can be overridden by a subclass
NotOverridable Procedure Indicates a procedure that cannot be overridden in a subclass
MustOverride Procedure Indicates a procedure that must be overridden in a subclass
Overrides Procedure Indicates that a procedure is overriding a procedure in a base class
Shadowed Procedure Indicate a property that shadows an inherited method with the same name.
Polymorphism: Method overloading
Overloading is a simple technique, to enable a single function name to accept parameters of different type. Class Adder
Overloads Public Sub Add(A as Integer, B as Integer)
Console.WriteLine (Convert.ToString(a + b))
End Sub
Overloads Public Sub Add(A as String, B as String)
Console.WriteLine ("Adding Strings: " + a + b)
End Sub
Shared Sub Main()
Dim AdderObj as Adder
'Create the object
AdderObj=new Adder
'This will invoke first function
AdderObj.Add(10,20)
'This will invoke second function
030010401 BCA 4th Semester
Preeti P Bhatt Department of Computer Science, UTU. 14 | P a g e
AdderObj.Add("hello"," how are you")
End Sub
End Class
Interface
Visual Basic .NET does not support multiple inheritance directly but using interfaces we can achieve multiple inheritance.
Interfaces allow us to create definitions for component interaction.
They also provide another way of implementing polymorphism.
Through interfaces, we specify methods that a component must implement without actually specifying how the method is implemented.
We just specify the methods in an interface and leave it to the class to implement those methods.
We use the Interface keyword to create an interface and implements keyword to implement the interface.
Once you create an interface you need to implement all the methods specified in that interface.
Syntax: Example:
Public Interface Interface_Name
Dim a as integer
Function FuncName(argumant) as Datatype
End Interface
Public Interface person
Sub SetName(ByVal PersonName As String)
Function GetName() As String
End Interface
Public Class employee
Implements person
Dim Name As String
Sub SetName(ByVal PersonName As String) Implements
person.SetName
Name = PersonName
End Sub
Function GetName() As String Implements person.GetName
Return Name
End Function
End Class
030010401 BCA 4th Semester
Preeti P Bhatt Department of Computer Science, UTU. 15 | P a g e
Abstract Class
• An abstract class is the one that is not used to create objects. • An abstract class is designed to act as a base class (to be inherited by other classes). • Abstract class is a design concept in program development and provides a base upon
which other classes are built. • Abstract classes are similar to interfaces.
• After declaring an abstract class, it cannot be instantiated on it's own, It must be inherited.
• Like interfaces, abstract classes can specify members that must be implemented in inheriting classes.
• Unlike interfaces, a class can inherit only one abstract class. • Abstract classes can only specify members that should be implemented by all inheriting
classes.
Creating Abstract Class
• In Visual Basic .NET we create an abstract class by using the MustInherit keyword. • An abstract class like all other classes can implement any number of members. • Members of an abstract class can either be
– Overridable (all the inheriting classes can create their own implementation of the members)
– They can have a fixed implementation that will be common to all inheriting members.
• Abstract classes can also specify abstract members. Like abstract classes, abstract members also provide no details regarding their implementation.
• To declare an abstract member we use the MustOverride keyword. Abstract members should be declared in abstract classes.
Interface Abstract class
Interface is purely abstract in nature. Abstract is not purely abstract in nature.
Class can inherit multiple interface. Class can inherit only one abstract class.
In interface all methods are without implementation
In abstract class some methods are without implementation
Members of interface does not have any access modifier.
Members of abstract does have an access modifier
An interface cannot contain fields, constructor, destructor.
An abstract class can contain fields, Constructor, destructor.
A class implementing an interface has to implement all the methods of the interface
A class implementing an abstract class does not need to implement all the methods of the abstract class
If we add new method to interface then we have to implement that method everywhere where we have implemented interface
If we add new method to abstract then we don't have to implement that method everywhere where we have implemented abstract
030010401 BCA 4th Semester
Preeti P Bhatt Department of Computer Science, UTU. 16 | P a g e
Example:
Public MustInherit Class AbstractClass
'declaring an abstract class with MustInherit keyword
Sub div()
MsgBox("Hi")
End Sub
Public MustOverride Function Add() As Integer
Public MustOverride Function Mul() As Integer
'declaring two abstract members with MustOverride keyword
End Class
Public Class Calculation
Inherits AbstractClass
'implementing the abstract class by inheriting
Dim i As Integer = 20
Dim j As Integer = 30
'declaring two integers
'implementing the add method
Public Overrides Function Add() As Integer
Return i + j
End Function
Public Overrides Function Mul() As Integer
Return i * j
End Function
'implementing the mul method
End Class
Sub Main()
Dim abs As New Calculation()
'creating an instance of calculation
Console.WriteLine("Sum is" & " " & abs.Add())
Console.WriteLine("Multiplication is" & " " & abs.Mul())
'displaying output
Console.Read()
End Sub
End Module
030010401 BCA 4th Semester
Preeti P Bhatt Department of Computer Science, UTU. 17 | P a g e
Interfaced-based Polymorphism
• To implement polymorphism with interfaces is called interfaced based polymorphism. • You create an interface and implement it in a number of other classes.
Question Related to This Unit
1) Write note on creating properties event in a class. 2) Discuss on class modifiers. How to define a class? 3) Write about access modifiers used in class declaration. 4) How to create abstract class? Compare it with simple class. 5) Difference between abstract class and interface. 6) Short note on inheritance. 7) Write on interface. Explain interfaced polymorphism. 8) Difference between abstraction and inheritance.
Module Module1
Sub Main()
Dim a1 As New Animal()
Dim f1 As New Fish()
Display(a1)
Display(f1)
End Sub
Public Sub Display(ByVal AnimalObject As AnimalInterface)
AnimalObject.Breathe()
End Sub
End Module
Public Interface AnimalInterface
Sub Breathe()
End Interface
Public Class Animal
Implements AnimalInterface
Sub Breathe() Implements AnimalInterface.Breathe
MsgBox("Breathing...")
End Sub
End Class
Public Class Fish
Implements AnimalInterface
Sub Breathe() Implements AnimalInterface.Breathe
MsgBox("Bubbling...")
End Sub
End Class
030010401 BCA 4th Semester
Preeti P Bhatt Department of Computer Science, UTU. 18 | P a g e
Collections:
Visual Basic .NET Collections are data structures that holds data in different ways for flexible operations.
The important datastructres in the Collections are
o ArrayList o Queue o Hash Table o Stack
ArrayList
ArrayList is one of the most flexible data structure from VB.NET Collections.
ArrayList contains a simple list of values and very easily we can add, insert, delete , view etc..
It is very flexible because we can add without any size information, that is it grow dynamically and also shrink.
Syntax:
Dim arralist_name As new ArrayList()
e.g. Dim ItemList As New ArrayList ()
Important Operation of ArrayList Add : Add an Item in an ArrayList Insert : Insert an Item in a specified position in an ArrayList Remove : Remove an Item from ArrayList RemoveAt: remove an item from a specified position Sort : Sort Items in an ArrayList
ADD Syntax: ArrayList.add(Item)
Item: The Item to be add the ArrayList
Example
Dim ItemList As New ArrayList ()
ItemList.Add("Item4")
Insert
Syntax: ArrayListName.insert (index, item)
Index: The position of the item in an ArrayList
Item: The Item to be add the ArrayList
Example
ItemList.Insert(3, "item6")
030010401 BCA 4th Semester
Preeti P Bhatt Department of Computer Science, UTU. 19 | P a g e
Remove
Remove Item
Syntax: ArrayList.Remove (item)
Item: The Item to be removed from the ArrayList
Example:
ItemList.Remove ("item2")
Remove Item from specific position
Syntax: ArrayList.RemoveAt (index)
Index: the position of an item to remove from an ArrayList
Example:
ItemList.RemoveAt (2)
Sort
Syntax: ArrayList.Sort()
Example: Itemlist.Sort()
Queue
The Queue is another data structure from VB.NET Collections .
Queue works like First In First Out method and the item added first in the Queue is first get out from Queue.
o We can Enqueue (add) items in Queue o We can Dequeue (remove from Queue ) o We can Peek (that is get the reference of first item added in Queue ) the item from Queue
Syntax:
Dim QueueName As New Collections.Queue
Ex: Dim qlist As New Collection.Queue
Operation on Queue
Enqueue : Add an Item in Queue
Syntax: Stack.Enqueue(Object) Object
Object: The item to add in Queue
Dequeue : Remove the oldest item from Queue (we dont get the item later)
Syntax: Stack.Dequeue()
Returns: Remove the oldest item and return.
Peek : Get the reference of the oldest item (it is not removed permenantly)
Syntax: Stack.Peek()
returns: Get the reference of the oldest item in the Queue
030010401 BCA 4th Semester
Preeti P Bhatt Department of Computer Science, UTU. 20 | P a g e
Example:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal
e As System.EventArgs) Handles Button1.Click
Dim queueList As New Collections.Queue
queueList.Enqueue("Sun")
queueList.Enqueue("Mon")
queueList.Enqueue("Tue")
queueList.Dequeue()
MsgBox(queueList.Peek())
Dim str As String
For Each str In queueList
MsgBox(str)
Next
End Sub
End Class
Traversing in collection
For traversing in collection we can use For Loop or For Each Loop.
It can be used with Array, ArrayList, Queue etc.
Using For Each Loop Dim ItemList As New ArrayList()
Dim k As String
For Each k In ItemList
MsgBox(k)
Next
Using For Loop Dim i As Integer
For i = 0 To ItemList.Count - 1
MsgBox(ItemList(i))
Next