Upload
meljun-cortes
View
15
Download
2
Embed Size (px)
Citation preview
Visual Basic .NET Programming
Object Oriented Programming Concepts * Property of STI Page 1 of 11
TOPIC TITLE: Object-Oriented Programming Concepts Specific Objectives: At the end of the topic session, the students are expected to: Cognitive:
1. Explain constructor. 2. Describe the Sub New() sub routine. 3. Explain destructor. 4. Explain how to initialize an object. 5. Explain the garbage collection concept. 6. Explain what Inheritance is. 7. Discuss the different keywords in overriding. 8. Explain overloading. 9. Differentiate MyBase from MyClass keyword. 10. Explain what an Interface is and identify the use of Interface
keyword. 11. Explain what polymorphism is.
Affective:
1. Listen to others with respect. 2. Participate in class discussions actively.
MATERIALS/EQUIPMENT:
o topic slides o OHP
TOPIC PREPARATION:
o Have the students research on the following: � Inheritance � Polymorphism
o It is imperative for the instructor to incorporate various kinds of teaching strategies while discussing the suggested topics. The instructor may use the suggested learning activities below to facilitate a thorough and creative discussion of the topic.
o Prepare the slides to be presented in the class.
TOPIC PRESENTATION: The topic will revolve around the overview of classes and objects. This will be the suggested flow of discussion for the course topic:
1. Introduce to the students the topics to be covered in this session.
2. Explain constructor. 3. Explain the Sub New() sub routine and provide example. 4. Explain destructor and give an example. 5. Explain how to initialize an object by providing some examples. 6. Explain the garbage collection concept. Also, give an example
on how to use the Dispose method. 7. Ask the students to share their research about Inheritance. 8. Explain what Inheritance is. Enumerate the different Inheritance
keywords and provide examples. 9. Explain what overriding is and discuss the different overriding
Visual Basic .NET Programming
Object Oriented Programming Concepts * Property of STI Page 2 of 11
keywords. 10. Explain overloading by providing an example. 11. Explain the MyBase and MyClass keywords by providing
examples on how to use these keywords. 12. Explain what an Inheritance is. 13. Ask the students to share their research about Polymorphism. 14. Explain what polymorphism is and give an example.
Visual Basic .NET Programming
Object Oriented Programming Concepts * Property of STI Page 3 of 11
Constructor Page 1 of 20
Object-Oriented Programming Concepts
Visual Basic .NET Programming
* Property of STIPage 1 of 20
ConstructorConstructorConstructorConstructor
� a special procedure used in initializing new objects
� Sub New constructor is used to perform the object initialization
Constructor In Visual Basic 6.0, the initialization of a class is placed in the Class_Initialize event of the class. This event is executed when the object is instantiated and it is used to set initial values of local variables, to open resources and to instantiate other objects. In Visual Basic .NET, the constructor is a special procedure used in initialization of new objects. The Class_Initialize event is replaced by the Sub New constructor to perform the object initialization. This procedure
is always executed once before any other code in a class. The Sub
New constructor can be explicitly invoked in the first line of code of
another constructor from either the same class or a derived class using the MyBase keyword.
[Constructor, Page 1 of 20]
Sub New Example Page 2 of 20
Object-Oriented Programming Concepts
Visual Basic .NET Programming
* Property of STIPage 2 of 20
Sub New ExampleSub New ExampleSub New ExampleSub New Example
� Default Constructor
Public Class Student
Public Sub New()
‘default constructor
‘start of initialization
intCnt = 1
End Sub
End Class
Sub New Example Page 3 of 20
Object-Oriented Programming Concepts
Visual Basic .NET Programming
* Property of STIPage 3 of 20
Sub New ExampleSub New ExampleSub New ExampleSub New Example
� Overloaded Constructor
Public Class Student
Public Sub New()
‘default constructor
‘start of initialization
intCnt = 1
End Sub
Public Sub New(ByVal x As
Integer)
‘overloaded constructor
‘start of initialization
intCnt = 1
End Sub
End Class
Sub New Example Public Class Student
Public Sub New()
‘start of initialization
intCnt = 1
End Sub
End Class
Another feature of using constructor is that it can be overloaded. Meaning, the New subroutine can be created as many as required. An
example of overloaded constructor is shown below: Public Class Student
Public Sub New()
‘start of initialization
intCnt = 1
End Sub
Public Sub New(ByVal x As Integer)
‘start of complex initialization
intCnt = x
End Sub
Public Sub New(ByVal x As Integer, ByVal m As
String)
‘start of initialization
intCnt = x
strMsg = m
End Sub
Visual Basic .NET Programming
Object Oriented Programming Concepts * Property of STI Page 4 of 11
End Class
[Sub New Example, Pages 2-3 of 20]
Destructor Page 4 of 20
Object-Oriented Programming Concepts
Visual Basic .NET Programming
* Property of STIPage 4 of 20
DestructorDestructorDestructorDestructor
� In Visual Basic .NET, the destruction of
objects can now be controlled using
destructors
� The Finalize destructor is executed
when the object is destroyed
� Example
Protected Overrides Sub Finalize()
‘close connection of other
resources
conn.Close
End Sub
Destructor In Visual Basic 6.0, objects are destroyed using the Class_Terminate event. In Visual Basic .NET, the destruction of objects can now be controlled using destructors. The Finalize destructor replaces the
Class_Terminate event. The Finalize destructor is executed when
the object is destroyed. Usually, this subroutine is used to perform clean up of open resources such as database connections and to release other objects. Finalize Example
Protected Overrides Sub Finalize()
‘close connection of other resources
conn.Close
End Sub
[Destructor, Page 4 of 20]
Initializing Objects Page 5 of 20
Object-Oriented Programming Concepts
Visual Basic .NET Programming
* Property of STIPage 5 of 20
Initializing ObjectsInitializing ObjectsInitializing ObjectsInitializing Objects
� An example of default constructor
Dim x As TestClass = New
TestClass()
� An example of overloaded constructor
Dim x As TestClass = New
TestClass(100)
� Another example of overloaded
constructor
Dim x As TestClass = New
TestClass(100, “Hello”)
Initializing Objects To initialize an object, you use the New keyword and invoke either the
default constructor or the overloaded constructor. An example of using the default constructor is shown below:
Dim x As TestClass = New TestClass()
An example of using the overloaded constructor is shown below:
Dim x As TestClass = New TestClass(100)
Another example of overloaded constructor:
Dim x As TestClass = New TestClass(100,“Hello”)
[Initializing Objects, Page 5 of 20]
Garbage Collection Garbage collection is a new feature in Visual Basic .NET. Garbage collection is a background process that traces object references, cleans up unused variables and destroys those that cannot be reached by executing code. To enable garbage collection, set x = Nothing. When enabled, the
garbage collection introduces a time delay between when the last reference to an object is removed and when the collector destroys the object and reclaims the memory. This time delay is significant for very complex and sensitive applications. Thus, to force garbage collection you can use the Garbage Collector (GC) class and invoke the
class’s Collect method.
Visual Basic .NET Programming
Object Oriented Programming Concepts * Property of STI Page 5 of 11
Garbage Collection Page 6 of 20
Object-Oriented Programming Concepts
Visual Basic .NET Programming
* Property of STIPage 6 of 20
Garbage CollectionGarbage CollectionGarbage CollectionGarbage Collection
� a background process that traces object
references, cleans up unused variables
and destroys those that cannot be
reached by executing code
� To enable garbage collection, set:
x = Nothing
� Dispose method provides flexibility in
releasing resources manually
Garbage Collection Page 7 of 20
Object-Oriented Programming Concepts
Visual Basic .NET Programming
* Property of STIPage 7 of 20
Garbage CollectionGarbage CollectionGarbage CollectionGarbage Collection
� Dispose method Example:
Public Sub Dispose()
‘close a database connection
conn.Close
End Sub
Protected Overrides Sub Finalize()
‘optional call to Dispose
Dispose()
End Sub
‘Client code
Dim x as TestClass = New
TestClass()
‘call the object’s dispose method
x.Dispose()
GC.Collect()
However, the use of the Collect method is not recommended because
it also collects other unused objects resulting to poor performance. It should be used with precaution.
An alternative way to release resources is by using the Dispose
method. This method provides flexibility in releasing resources manually. When objects resources are no longer needed, a client code can directly call coded placed in the Dispose method of the object. If
the client code does not call the Dispose method explicitly before
garbage collection occurs, the Finalize method of the class can also
call the Dispose method.
Example on how to use the Dispose method is given below:
Public Sub Dispose()
Conn.Close ‘close a database connection
End Sub
Protected Overrides Sub Finalize()
Dispose() ‘optional call to Dispose
End Sub
‘Client code
Dim x as TestClass = New TestClass()
x.Dispose() ‘call the object’s dispose method
[Garbage Collection, Pages 6-7 of 20]
Inheritance Page 8 of 20
Object-Oriented Programming Concepts
Visual Basic .NET Programming
* Property of STIPage 8 of 20
InheritanceInheritanceInheritanceInheritance
� backbone of object-oriented programming
� enables programmers to create a
hierarchy among a group of classes that
have similar characteristics
� allows creating a class from an existing
base class
� Inheritance keywords
� Inherits
� NotInheritable
� MustInherit
� Protected
Inheritance
Inheritance Inheritance is the backbone of object-oriented programming. It enables programmers to create a hierarchy among a group of classes that have similar characteristics. We can have one class that defines all the attributes and behavior common to a specific group of classes. All classes that are part of this specific group can inherit the common attributes and behavior from this common class. Let us understand what inheritance is by taking a real world example. Assume that we want to create a class called SUV, which has the same features as the class called Vehicle. One way of doing this is to re-declare the member variables called attributes and the methods (behavior) already available in the Vehicle class in the SUV class also and then add the special features of the SUV. Inheritance allows creating a class from an existing base class. The class is also called as the derived class. The derived class can inherit all the base class properties, methods, members, events and event handlers. Thus, inheritance makes it easy to reuse the base class throughout an application.
Visual Basic .NET Programming
Object Oriented Programming Concepts * Property of STI Page 6 of 11
Page 9 of 20
Object-Oriented Programming Concepts
Visual Basic .NET Programming
* Property of STIPage 9 of 20
InheritanceInheritanceInheritanceInheritance
� Inherits keyword
Public Class HumanResources
Inhertis Department
…
End Class
� NotInheritable keyword
Public Class NotInheritable Shape
…
End Class
Public Class Circle
Inherits Shape
‘it will generate a compile
error
End Class
Inheritance Page 10 of 20
Object-Oriented Programming Concepts
Visual Basic .NET Programming
* Property of STIPage 10 of 20
InheritanceInheritanceInheritanceInheritance
� MustInherit keyword
Public Class MustInherit People
…
End Class
‘client code
Dim emp1 As New People()
‘generates a compile error
� Protected keyword
Public Class Subject
‘ accessible anywhere
Public subCode As String
‘accessible only in this
class or a ‘derived class
Protected subDesc As String
End Class
Inheritance keywords:
• Inherits
• NotInheritable
• MustInherit
• Protected The Inherits keyword is used to define a derived class that will inherit
from an existing base class. An example is shown below: Public Class DerivedClass
Inherits BaseClass
…
End Class
Another example: Public Class HumanResources
Inherits Department
…
End Class
The NotInheritable keyword is used to define a class that cannot be
used as a base for inheritance. A compile error will be generated if another class attempts to inherit from the NotInheritable defined class. Example implementation is shown below. Public Class NotInheritable Shape
…
End Class
Public Class Circle
Inherits Shape
‘it will generate a compile error
End Class
The MustInherit keyword on the other hand is used to define a class
that is not intended to be used directly as instantiated objects. In other words, MustInherit keyword is used to create an abstract class. An abstract class is used to lay a foundation (in terms of behavior) for other classes. An example code is shown below: Public Class MustInherit People
…
End Class
‘client code
Dim emp1 As New People() ‘generates a compile error
The above code generates an error because the New keyword cannot be used to instantiate a MustInherit class. The Protected keyword is used to define special relationship among a
base class and its derived classes. It is used to allow a base class to create members that can only be accessed by its derived classes. An example is shown below: Public Class Subject
‘ accessible anywhere
Public subCode As String
‘accessible only in this class or a derived class
Protected subDesc As String
Visual Basic .NET Programming
Object Oriented Programming Concepts * Property of STI Page 7 of 11
End Class
[Inheritance, Pages 8-10 of 20]
Overriding Page 11 of 20
Object-Oriented Programming Concepts
Visual Basic .NET Programming
* Property of STIPage 11 of 20
OverridingOverridingOverridingOverriding
� used to create specific implementation
code not found in the base class
� Overriding Keywords
� Overridable
� MustOverride
� Overrides
� NotOverridable
Overriding Page 12 of 20
Object-Oriented Programming Concepts
Visual Basic .NET Programming
* Property of STIPage 12 of 20
OverridingOverridingOverridingOverriding
� Overridable keyword
Public Overridable Sub
MethodOverride()
MsgBox(“Base Class
MethodOverrirde”)
End Sub
� MustOverride keyword
Public MustOverride Sub
CalculateGPA()
End Sub
Overriding Page 13 of 20
Object-Oriented Programming Concepts
Visual Basic .NET Programming
* Property of STI
Page 13 of 20
OverridingOverridingOverridingOverriding
� Overriden keyword
Public Overrides Sub
MethodOverride()
MsgBox(“Derived Class
MethodOverride”)
End Sub
� NotOverridable keyword
Public NotOverridable Overrides
Sub MethodOverride()
MsgBox(“Derived Class
MethodOverride”)
End Sub
Overriding Overriding is a technique used in derived classes to create specific implementation code not found in the base class rather than using the inherited methods. The following are keywords that can be used in implementing overriding:
• Overridable
• MustOverride
• Overrides
• NotOverridable To make a property, function or sub routine in the base class overridable, the Overridable keyword is specified. This will allow the
derive class to create specific implementation of the class members. An example is shown below: Public Overridable Sub MethodOverride()
MsgBox(“Base Class MethodOverride”)
End Sub
The MustOverride keyword is used only in a base class that is marked
as MustInherit. This keyword is used to create a base class member
that must be overridden in all derived classes. It is created in the base class with no implementation. An example is shown below: Public MustOverride Sub CalculateGPA()
End Sub
The Overriden keyword is used to specify that a derived class method
overrides the implementation of the base class method. A compile error occurs if an Overridden method is defined in the derived class and is
not specified in the base class as Overridable. The method signature
must exactly match the method being overridden except for the parameter names. An example is shown below: Public Overrides Sub MethodOverride()
MsgBox(“Derived Class MethodOverride”)
End Sub
The NotOverridable keyword is used in the derived class to stop
subsequent inheritance from overriding the method. The following example shows how to declare a derived class method that overrides the base class implementation but does not allow any further overriding. Public NotOverridable Overrides Sub MethodOverride()
MsgBox(“Derived Class MethodOverride”)
End Sub
[Overriding, Pages 11-13 of 20]
Visual Basic .NET Programming
Object Oriented Programming Concepts * Property of STI Page 8 of 11
Overloading Page 14 of 20
Object-Oriented Programming Concepts
Visual Basic .NET Programming
* Property of STI
Page 14 of 20
OverloadingOverloadingOverloadingOverloading
� creating a function or sub routine with the
same name as defined in the base class
but with different signatures
� uses Overloads keyword
� Example:
Public Overloads Sub Display(ByVal
x As Integer)
MsgBox(“Derive Class Display –
Overloaded method”)
End Sub
Overloading Overloading is creating a function or sub routine with the same name as defined in the base class but with different signatures. The Overloads
keyword is used for this purpose. The signature must include different parameters or parameter types. An example is shown below: Public Overloads Sub Display(ByVal x As Integer)
MsgBox(“Derive Class Display – Overloaded
method”)
End Sub
[Overloading, Page 14 of 20]
Using MyBase and MyClass Keywords Page 15 of 20
Object-Oriented Programming Concepts
Visual Basic .NET Programming
* Property of STI
Page 15 of 20
Using Using Using Using MyBaseMyBaseMyBaseMyBase and and and and MyClassMyClassMyClassMyClass KeywordsKeywordsKeywordsKeywords
� MyBase keyword
Public Class DerivedClass
Inherits BaseClass
Public Sub New()
MyBase.New() ‘a call to the
constructor of the base class
intCtr = 1
End Sub
Public Overrides Sub
OverrideMethod()
MsgBox(“Derived
OverrideMethod”)
MyBase.OverrideMethod()
‘ call the original method
End Sub
End Class
Using MyBase and MyClass Keywords Page 16 of 20
Object-Oriented Programming Concepts
Visual Basic .NET Programming
* Property of STI
Page 16 of 20
Using Using Using Using MyBaseMyBaseMyBaseMyBase and and and and MyClassMyClassMyClassMyClass KeywordsKeywordsKeywordsKeywords
� MyClass keyword
Public Class Computer
Public Overridable Sub
CalculateMemory()
MsgBox(“BaseOverrideMethod”)
End Sub
Public Sub Display()
MyClass.CalculateMemory()
‘will call base method
End Sub
End Class
Public Class Desktop
Inherits Computer
Public Overrides Sub
CalculateMemory()
MsgBox(“Derivex
OverrideMethod”)
End Sub
End Class
‘client code
Dim comp1 As Desktop = New Desktop()
comp1.Display()
Using MyBase and MyClass Keywords
The MyBase keyword is used to access the immediate base class from
which a derived class is inheriting. It cannot be used to access classes higher in the class hierarchy. A common practice is to use MyBase in constructors and destructors where you want to access the code in the overridden method. Public Class DerivedClass
Inherits BaseClass
Public Sub New()
MyBase.New() ‘a call to the constructor
of the base class
intCtr = 1
End Sub
Public Overrides Sub OverrideMethod()
MsgBox(“Derived OverrideMethod”)
MyBase.OverrideMethod()
‘ call the original method
End Sub
End Class
The MyClass keyword is used to invoke the Overridable method in
the base class rather than the overridden method in the derived class. It ensures that the base class implementation of an overridable method is called. An example is shown below: Public Class Computer
Public Overridable Sub CalculateMemory()
MsgBox(“Base OverrideMethod”)
End Sub
Public Sub Display()
MyClass.CalculateMemory()
‘will call base method
End Sub
End Class
Public Class Desktop
Inherits Computer
Visual Basic .NET Programming
Object Oriented Programming Concepts * Property of STI Page 9 of 11
Public Overrides Sub CalculateMemory()
MsgBox(“Derived OverrideMethod”)
End Sub
End Class
‘client code
Dim comp1 As Desktop = New Desktop()
comp1.Display()
The above example will invoke the CalculateMemory() sub routine of
the class Computer. Note that the CalculateMemory() sub routuine
is an overridden method. The use of MyClass keyword specifies that
the method to be called is the method defined in the base class.
[Using MyBase and MyClass Keywords, Pages 15-16 of 20]
Interface Page 17 of 20
Object-Oriented Programming Concepts
Visual Basic .NET Programming
* Property of STI
Page 17 of 20
InterfaceInterfaceInterfaceInterface
� captures the roles played by various
classes that implement the interfaces
� specifies the prototype or behavior of a
class
� defines signatures for procedures,
properties and events but contains no
implementation code
� Interface keyword
• used to explicitly create an interface
without creating a class
� Implements keyword
• used to implement the interface
Interface Page 18 of 20
Object-Oriented Programming Concepts
Visual Basic .NET Programming
* Property of STI
Page 18 of 20
InterfaceInterfaceInterfaceInterface
� Example:
Interface IShape
Function Method1(ByRef s As
String) As Boolean
Sub Method2()
Sub Method2(ByVal x As Integer)
End Interface
� Class Implementing IShape interface:
Public Class Polygon Implements
IShape
….
End Class
Interface An interface essentially captures the roles played by various classes that implement the interfaces. An interface specifies the prototype or behavior of a class. All methods declared in an interface are abstract methods which mean no implementation code. If a class agrees to implement an interface it must implement all of the properties and methods defined. Interface defines signatures for procedures, properties and events but contains no implementation code. The Interface keyword is used to
explicitly create an interface without creating a class. It can be defined in the Declaration section of the module. An interface can also inherit
another interface. The Implements keyword is used to implement the
interface. An example interface implementation is shown below: Interface IShape
Function Method1(ByRef s As String) As Boolean
Sub Method2()
Sub Method2(ByVal x As Integer)
End Interface
This means that if a class implements the IShape interface it will have to implement these routines. Here’s an example of a class implementing this interface: Public Class Polygon Implements IShape
….
End Class
[Interface, Pages 17-18 of 20]
Visual Basic .NET Programming
Object Oriented Programming Concepts * Property of STI Page 10 of 11
Polymorphism Page 19 of 20
Object-Oriented Programming Concepts
Visual Basic .NET Programming
* Property of STI
Page 19 of 20
PolymorphismPolymorphismPolymorphismPolymorphism
� means “one name in multiple forms”
� in VB.Net, it can be achieved by using interfaces and inheritance
Polymorphism Page 20 of 20
Object-Oriented Programming Concepts
Visual Basic .NET Programming
* Property of STI
Page 20 of 20
PolymorphismPolymorphismPolymorphismPolymorphism
� Example:
‘IPerson interface definition
Interface IPerson
Property LastNameI() As String
Sub Display()
End Interface
Class Employee ‘Employee class definition
Implements IPerson
Private strName As String
Private strCompany As String
Public Sub Display() Implements IPerson.Display
MsgBox(strCompany & “ honors “ & strName)
End Sub
Private Property LastName() As String Implements IPerson.LastName()
Get
Return strName
End Get
Set (ByVal val As String)
End Set
End Property
End Class
Polymorphism Polymorphism is another pillar in object-oriented programming. It means “one name in multiple forms”. Using polymorphism, many functions or sub routines can be created but with different argument list. The exact function or sub routine to be invoked will be determined by checking the type and number of arguments in the function. Polymorphism in VB.Net can be achieved by using interfaces and inheritance. Interfaces are created explicitly by using a combination of the Interface and
Implements keywords. An example is shown below:
‘IPerson interface definition
Interface IPerson
Property LastNameI() As String
Sub Display()
End Interface
‘Employee class definition
Class Employee
Implements IPerson
Private strName As String
Private strCompany As String
Public Sub Display() Implements
IPerson.Display
MsgBox(strCompany & “ honors “ & strName)
End Sub
Private Property LastName() As String
Implements IPerson.LastName()
Get
Return strName
End Get
Set (ByVal val As String)
End Set
End Property
End Class
[Polymorphism, Pages 19-20 of 20]
EVALUATION/GENERALIZATION:
• A constructor is the primary method of a class. It allows the programmer to initialize a variable of a class when the class is instantiated.
• A class can have multiple constructors.
• Regardless the name of the class, the constructor in VB.NET is called New.
• The Finalize() method is automatically called when an
instance of a class is not needed anymore.
• Garbage collection is a background process that traces object references, cleans up unused variables and destroys those that cannot be reached by executing code.
• The derived class can inherit all the base class properties, methods, members, events and event handlers.
Visual Basic .NET Programming
Object Oriented Programming Concepts * Property of STI Page 11 of 11
• An interface is a class that creates a foundation that new derived classes can use.
REFERENCES:
� Microsoft Official Course, (2002), 2373B: Programming with
Microsoft Visual Basic .NET, Microsoft Corporation � Holzner, Steven, (2003), Sams teach yourself Microsoft Visual
Basic.Net 2003 in 21 days, USA, Sams Publishing � Liberty, Jesse, (2003), Learning Visual Basic .NET, USA,
O'Reilly & Associates, Inc