Lecture 10 OOP and VB.Net
Pillars of OOP Objects and Classes Encapsulation Inheritance Polymorphism Abstraction
Classes A class is a template for an object. An object will have attributes and properties. The class template can be obtained from the add options Should start with a class declaration statement and end with an End Class statement By default, windows application projects are written in classes containing Procedures, event handlers and data members. Before classes were created in VB 3, only structures were used.
Origion of OOP Allow one to create objects Example: Structures Public Class Form1 Private Structure Creature Dim NumberOfLegs As Integer Dim Length As Integer End Structure Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim InsectList = New List(Of Creature) Dim MyInsect As New Creature MyInsect.NumberOfLegs = 100 MyInsect.Length = 2000 InsectList.Add(MyInsect) For Each Bug As Creature In InsectList MsgBox(Bug.NumberOfLegs) Next End Sub End Class
Structures vs Classes Similarities Structures and classes are similar in the following respects: Both are container types, meaning that they contain other types as members. Both have members, which can include constructors, methods, properties, fields, constants, enumerations, events, and event handlers. Members of both can have individualized access levels. For example, one member can be declared Public and another Private. Both can implement interfaces.(note: Read on and understand). Both can have shared constructors, with or without parameters. Both can expose a default property, provided that property takes at least one parameter. Both can declare and raise events, and both can declare delegates.
Differences Structures and classes differ in the following particulars: Structures are value types; classes are reference types. A variable of a structure type contains the structure's data, rather than containing a reference to the data as a class type does. All structure elements are Public by default; class variables and constants are Private by default, while other class members are Public by default. A structure must have at least one nonshared variable or nonshared, noncustom event element; a class can be completely empty. Structure elements cannot be declared as Protected; class members can. A structure procedure can handle events only if it is a Shared Sub procedure, and only by means of the AddHandler Statement; any class procedure can handle events, using either the Handles Clause keyword or the AddHandler statement. Structure variable declarations cannot specify initializers or initial sizes for arrays; class variable declarations can. Structures are not inheritable; classes are. Structures are never terminated, so the common language runtime (CLR) never calls the Finalize method on any structure; classes are terminated by the garbage collector (GC), which calls Finalize on a class when it detects there are no active references remaining. A structure does not require a constructor; a class does.
Inheritance It is the ability to use all of the functionality of an existing class and extend those capabilities without re-writing the class. Allows building of a set of related classes organized in a hierarchy allowing use and reuse of code. We can create a class and derive another class from it using the inherits statement.
The diagram above demonstrates the geometric shapes object model. Squares, circles, triangles, rectangles, pentagons, hexagons and octagons are geometric shapes.
We can use OOP to store common state and behavior of a category of objects. Particular objects can inherit the common state and behavior of the generic object. Each object(instance) will then need to define its own special state and behavior. For example, each shape has its own formula to define area and parameter. Inheritance allows code re-use and makes it less repetitive An object model for the shape is demonstrated below.
The shape class is the parent class. Square, circle and rectangle are derived. To create a derived class in VB.Net, the class declaration is done as follows: Class child Inherits parent End Class Code
Example Module Module1 Sub Main() End Sub Public Class Account Private mcode As String 'Account Code Private mname As String 'Account Name Private mdescription As String 'Account Description Protected Balance As Double 'Account Balance End Class Public Class BankAccount Inherits Account Double) Dim NewBalance As Double NewBalance = Balance + amount Balance = NewBalance End Sub Public Sub withdraw(byval amount As Double) Dim newbalance As Double newbalance = Balance - amount Balance = newbalance End Sub End Class End Module Public Sub Deposit(ByVal amount As
The following terms are often used interchangeably: i. Super class: Parent class or base class ii. Sub Class: Child Class or derived class A simple real-world example useful in explaining inheritance is the shape class_ Squares, circles, triangles, rectangles, e.t.c all form the class of geometric figures.
Abstraction It is the process of identifying common patterns that have systemic variations. An abstraction represents the common pattern and provides the means for specifying which variation to use. An abstract class is a parent class that allows inheritance but can never be instantiated. Abstract classes contain one or more abstract methods that do not have implementation. For example, suppose you create a Person object because you want to deal with a generic person. You may decide that there is nothing you can do with the person class without adding some some specific behaviors or data. So you may choose to make the person class an abstract class.
Abstract classes are closely related to interfaces. An abstract class is denoted in VB with the keyword MustInherit.
Example Module Module1 Sub Main() End Sub Public MustInherit Class WashingMachine Sub New() End Sub Public MustOverride Sub Wash() Public MustOverride Sub Rinse(loadSize As Integer) Public MustOverride Function Spin(speed As Integer) As Long End Class Public Overrides Sub Rinse(loadSize As Integer) End Sub Public Overrides Function Spin(speed As Integer) As Long Return 0 End Function Public Overrides Sub Wash() End Sub End Class End Module Public Class MyWashingMachine Inherits WashingMachine
Encapsulation The process of covering up the data and functions into a single unit called a class. Hiding the code and data into a single unit to protect the data from the outside world. It means hiding or securing data from outside functions. The data is strictly bound with function members declared in the same class. We hide the data from direct interaction.
Polymorphism Allows objects to be represented in multiple forms. Even though classes are inherited or derived from the same parent class, each derived class will have its own behavior. It is linked to inheritance. It is the ability to vary the implementation of a method or property. The same method or property can perform different actions depending on the run-time type of instance that invokes it.
Example Module Module1 Sub Main() Dim Z As Base Z = New Base() Z.X = 10 Z = New Derived() Z.X = 10 End Sub Class Base Public Overridable Property X() As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class Class Derived Inherits Base Public Overrides Property X() As Integer Get Return 0 End Get Set(value As Integer) End Set End Property End Class End Module
Interfaces An interface is a class that creates a foundation that new derived classes can use by defining the origional behavior that deriving classes would use. You do not implement the members of the interface. To create an interface, you start with the Interface keyword followed by the name of the interface. You end the interface definition with an End Interface line. By tradition or good habit, the name of an interface starts with I. Example: Public Interface ITriangle Code End Interface Interface members must be methods, properties, events or type definition.
After creating an interface, you can derive a class from it. When deriving from an interface, instead of the Inherits keyword, you use Implements followed by the name of the interface. Example: Public Interface ITriangle End Interface Public Class RegularTriangle Implements ITriangle End Class Once you have derived the class, you can create objects from it and instantiate it using the New operator. Module Exercise Public Function Main() As Integer Dim reg As RegularTriangle reg = New RegularTriangle Return 0 End Function End Module
You must implement each member of the interface in the derived class. If you omit implementing a member of the parent interface, you would receive an error. When implementing a member of the interface, it When implementing a member of the interface, it must be followed by the Implements keyword, the name of the interface, the period operator, and the name of the member that it is implementing.
Example Interface IValue Sub Render() End Interface Class Content : Implements IValue Public Sub Render() Implements IValue.Render Console.WriteLine("Content.Render") End Sub End Class Class Image : Implements IValue Public Sub Render() Implements IValue.Render Console.WriteLine("Image.Render") End Sub End Class