IT 107 Object Oriented Programming

You might also like

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

INFOTECH COLLEGE OF ARTS AND SCIENCES PHILIPPINES

Pasig City

STUDY GUIDE MODULE IN

Object Oriented
Programming

2020
Page
Lesson 1 - Introduction to Object Oriented Programming in VB.NET
The invention of object-oriented programming, OOP hereinafter, was no coincidence, but the result of a
development which led to its creation. It's a modern software development methodology supported by
most programming languages. A common mistake is that people think that OOP should only be used for
certain kinds of programs and that for other cases it would be needlessly complicated; however, the
opposite has proven to be true. OOP is a new way of looking at a program and the communication
between its parts. The OOP is not just a technology or a recommended program structure, it's mainly a
new way of thinking. A new perspective from which we could analyse problems and a new era in software
development.

The evolution of methodologies


There is a big difference between programming nowadays and programming 40 years ago. The first
computers didn't have great performance and their software was quite simple. The evolution of hardware
is so fast that the number of transistors in microprocessors doubles every year (Moore's Law).
Unfortunately, people aren't able to evolve as quickly as hardware does. Faster computers require more
and more sophisticated and complex software. So much that at one point, it was found out that about
90% of all software doesn't meet deadlines, requires additional costs or isn't finished at all. Developers
started looking for new ways to write programs. Several new approaches took turns. More precisely,
paradigms (ways of thinking). Listed as follows:

 Machine code -The program was just a set of instructions where we weren't able to name
variables or enter mathematical expressions. The source code was obviously specific for the then
current hardware (processor). This paradigm was replaced soon after it was established.
 Unstructured paradigm - The unstructured approach is similar to the assembly languages, it's a
set of instructions which are executed line by line. The source code wasn't dependent on the
hardware and was human readable. This approach enabled the creation of more complex
programs for a while. There were still many pitfalls: the only way to repeat something or to branch
off a code was the GOTO statement. GOTO allowed to "jump" to different locations within the
program. Locations were previously specified by a line number in the source code, which is
obviously impractical. When we insert a new line of code somewhere, the numbers no longer
match and the code is broken. Later, it was made possible to define what they then called "labels".
This approach served as a way of simulating loops. This method of writing programs is of course
very confusing and soon failed to be sufficient for developing complex programs.
 Structured programming - Structured programming is the first paradigm that lasted for a longer
time and was quite sufficient for the development of new programs. They would mostly program
using loops and branching. The program would be decomposed into functions, methods, that we
haven't discussed yet since Visual Basic .NET, which is an object-oriented language, doesn't even
allow us to declare them. There is a way to do it anyway, but I'd rather skip this intermediate step
and get right into OOP. In structured programming, we meet a functional decomposition principle.
A problem is decomposed into several sub problems and each sub problem is then solved with
some parametrized function. The disadvantage to it is that a function can only do one thing and
when we want a different behaviour, we have to write a new one. There is no way to reuse old
1
Page

code and modify it. We need to write it again and again - this creates unnecessary, potentially
costly, errors. However, such universal functions usually require a lot of parameters to pass and
are hard to use and maintain.

The object-oriented approach


OOP is a philosophy and a way of thinking, designing and implementing solutions that focuses
on reusability. This approach is inspired by the industrial revolution - the invention of basic components.
For example, when we build our house, we don't burn our own bricks and forge nails, we order them.

Making a "component program" is smarter and cheaper. Components don't fail, they're tested and
maintained. If there's a problem, it is most likely in the code you have written in one specific location.
We're motivated to write clear code since it can be used by others or by ourselves in other projects. Let's
face it, humans are lazy by nature and if we thought that our code wouldn't ever be reused, we simply
wouldn't write it good enough.

How the Object Oriented Programming works

It tries to simulate reality as we're used to see it. We can say that we
abandon the idea how the program is seen by the computer
(machine) and write it from the programmer's (human's) point of
view. As we had replaced the assembler with human-readable
mathematical notations, now we're going even further and replace
those, too. OOP is, therefore, a certain level of abstraction above the
program. This has significant advantages because it's more natural
and readable for us.

Lesson 2 - Introduction to .Net Framework


What is a .NET Framework?
NET Framework (pronounced as "dot net") is a software framework developed by Microsoft that runs
primarily on Microsoft Windows. It includes a large class library called Framework Class Library (FCL) and
provides language interoperability (each language can use code written in other languages) across
several programming languages. Programs written for .NET Framework execute in a software
environment (in contrast to a hardware environment) named the Common Language Runtime (CLR). The
CLR is an application virtual machine that provides services such as security, memory management, and
exception handling. As such, computer code written using .NET Framework is called "managed code".
FCL and CLR together constitute the .NET Framework

The Common Language Runtime and .NET Class Libraries


The .NET Framework provides a run-time environment called the common language runtime, which runs
the code and provides services that make the development process easier.

Compilers and tools expose the common language runtime's functionality and enable you to write code
2

that benefits from this managed execution environment. Code that you develop with a language
Page

compiler that targets the runtime is called managed code; it benefits from features such as cross-
language integration, cross-language exception handling, enhanced security, versioning and deployment
support, a simplified model for component interaction, and debugging and profiling services.

The runtime automatically handles object layout and manages references to objects, releasing them
when they are no longer being used. Objects whose lifetimes are managed in this way are called
managed data. Language compilers and tools expose the runtime's functionality in ways that are
intended to be useful and intuitive to developers. This means that some features of the runtime might
be more noticeable in one environment than in another. How you experience the runtime depends on
which language compilers or tools you use. For example, if you are a Visual Basic developer, you might
notice that with the common language runtime, the Visual Basic language has more object-oriented
features than before. The runtime provides the following benefits:

 Performance improvements.
 The ability to easily use components developed in other languages.
 Extensible types provided by a class library.
 Language features such as inheritance, interfaces, and overloading for object-oriented
programming.
 Support for explicit free threading that allows creation of multithreaded, scalable applications.
 Support for structured exception handling.
 Garbage collection
 Support for custom attributes.
 Use of delegates instead of function pointers for increased type safety and security. For more
information about delegates, see Common Type System..NET, .NET Core, .NET Standard,
Xamarin/Mono

The .NET Application


When building applications in .NET, it needs to follow a couple of rules. We'll look at the structure of an
application and which parts are necessary during runtime.

The Visual Studio Solution and Project


This page describes the concept of a project and a solution in Visual Studio. It also briefly covers the
Solution Explorer tool window and how to create a new project.

Projects
When you create an app or website in Visual Studio, you start with a project. In a logical sense, a project
contains all files that are compiled into an executable, library, or website. Those files can include source
code, icons, images, data files, and so on. A project also contains compiler settings and other
configuration files that might be needed by various services or components that your program
communicates with.

Project file
3

Visual Studio uses MSBuild to build each project in a solution, and each project contains an MSBuild
Page

project file. The file extension reflects the type of project, for example, a C# project (.csproj), a Visual
Basic project (.vbproj), or a database project (.dbproj). The project file is an XML document that contains
all the information and instructions that MSBuild needs in order to build your project, including the
content, platform requirements, versioning information, web server or database server settings, and the
tasks to perform.

Project files are based on the MSBuild XML schema. To look at the contents of newer, sdk-style project
files in Visual Studio, right-click on the project node in Solution Explorer and select Edit <projectname>.
To look at the contents of .NET Framework and other projects of that style, first unload the project
(right-click on the project node in Solution Explorer and select Unload Project). Then, right-click on the
project and choose Edit <projectname>.

Solutions
A project is contained within a solution. Despite its name, a solution is not an "answer". It's simply a
container for one or more related projects, along with build information, Visual Studio window settings,
and any miscellaneous files that aren't associated with a particular project. A solution is described by a
text file (extension .sln) with its own unique format; it's not intended to be edited by hand.

Visual Studio uses two file types (.sln and .suo) to store settings for solutions:

SOLUTIONS

Extension Name Description

.sln Visual Studio Solution Organizes projects, project items, and solution items in the solution.

.suo Solution User Options Stores user-level settings and customizations, such as breakpoints.

Create new projects


The easiest way to create a new project is to start from a project template for a particular type of
application or website. A project template consists of a basic set of pre-generated code files, config files,
assets, and settings. These templates are available in the dialog box where you create a new project
(File > New > Project). For more information, see Create a new project in Visual Studio and Create
solutions and projects.

If you often customize your projects in a certain way, you can create a custom project template that you
can then use to create new projects from. For more information, see Create project and item templates.

When you create a new project, it is saved by default at %USERPROFILE%\source\repos. You can change
this location in the Projects location setting under Tools > Options > Projects and Solutions > Locations.
For more information, see Projects and Solutions page, Options dialog box.
4
Page
Solution Explorer
After you create a new project, you can use Solution
Explorer to view and manage the project and solution and
their associated items. The following illustration
shows Solution Explorer with a C# solution that contains
two projects:

Many menu commands are available from the right-click


menu on various items in Solution Explorer. These
commands include building a project, managing NuGet
packages, adding a reference, renaming a file, and running
tests, just to name a few. The toolbar across the top
of Solution Explorer has buttons to switch from a solution
view to a folder view, show hidden files, collapse all nodes,
and more.

Tip

If you've closed Solution Explorer and you want to open it


again, choose Window > Reset Window Layout from the
menu bar.

Namespace and Assembly


A .Net Namespace provides the fundamental unit of logical code grouping while an assembly provides a
fundamental unit of physical code grouping.

Namespace

Namespaces is a logical group of related classes that can be used by any other language targeting the
Microsoft .Net framework. It is more used for logical organization of your classes. Namespaces are a way
of grouping type names and reducing the chance of name collisions.

Hierarchy and Fully-Qualified Names

The fully qualified name of a class is constructed by concatenating the names of all the
namespaces that contain the type. For e.g. the fully qualified name of the TextBox class is
System.Windows.Forms.TextBox . That means TextBox class is contained in the Forms
namespace that is contained in the Windows namespace that is contained in the root System
namespace.

Assembly

An assembly is a collection of types and resources that are built to work together and form a logical unit
of functionality. It is an Output Unit, that is .exe or .dll file. It is a unit of Deployment and a unit of
5

versioning and also it contain MSIL (Microsoft Intermediate Language) code. Assemblies are self-
Page
describing, it contains all the metadata about the modules, types, and other elements in the form of a
manifest. Assemblies are of two types: Private and Shared Assemblies.

Private assembly is intended only for one application. The files of that assembly must be placed
in the same folder of the application.

Shared assembly is to be made into a Shared Assembly, then the naming conventions are very
strict since it has to be unique across the entire system

Lesson 3 - Objects and classes


Object
An object is a combination of code and data that can be treated as a unit. An object can be a piece of an
application, like a control or a form. An entire application can also be an object.

When you create an application in Visual Basic, you constantly work with objects. You can use objects
provided by Visual Basic, such as controls, forms, and data access objects. You can also use objects from
other applications within your Visual Basic application. You can even create your own objects and define
additional properties and methods for them. Objects act like prefabricated building blocks for programs
— they let you write a piece of code once and reuse it over and over.

Classes
Each object in Visual Basic is defined by a class. A class describes the variables, properties, procedures,
and events of an object. Objects are instances of classes; you can create as many objects you need once
you have defined a class.

To understand the relationship between an object and its class, think of cookie cutters and cookies. The
cookie cutter is the class. It defines the characteristics of each cookie, for example size and shape. The
class is used to create objects. The objects are the cookies. You must create an object before you can
access its members, except for Shared members which can be accessed without an object of the class.

Create an object from a class


 Determine from which class you want to create an object, or define your own class. For
example:

Public Class Customer


Public Property AccountNumber As Integer
End Class

 Write a Dim Statement to create a variable to which you can assign a class instance. The variable
should be of the type of the desired class.

Dim nextCustomer As Customer


6
Page

 Add the New Operator keyword to initialize the variable to a new instance of the class.
Dim nextCustomer As New Customer

 You can now access the members of the class through the object variable.

nextCustomer.AccountNumber = lastAccountNumber + 1

Note: Whenever possible, you should declare the variable to be of the class type you intend to assign to
it. This is called early binding. If you don't know the class type at compile time, you can invoke late
binding by declaring the variable to be of the Object Data Type. However, late binding can make
performance slower and limit access to the run-time object's members. For more information,
see Object Variable Declaration.

Multiple instances
Objects newly created from a class are often identical to each other. Once they exist as individual
objects, however, their variables and properties can be changed independently of the other instances.
For example, if you add three check boxes to a form, each check box object is an instance of
the CheckBox class. The individual CheckBox objects share a common set of characteristics and
capabilities (properties, variables, procedures, and events) defined by the class. However, each has its
own name, can be separately enabled and disabled, and can be placed in a different location on the
form.
Object members - An object is an element of an application, representing an instance of a class. Fields,
properties, methods, and events are the building blocks of objects and constitute their members.
Member Access - You access a member of an object by specifying, in order, the name of the object
variable, a period (.), and the name of the member. The following example sets the Text property of
a Label object.

warningLabel.Text = "Data not saved"

IntelliSense listing of members

IntelliSense lists members of a class when you invoke its List Members option, for example when you
type a period (.) as a member-access operator. If you type the period following the name of a variable
declared as an instance of that class, IntelliSense lists all the instance members and none of the shared
members. If you type the period following the class name itself, IntelliSense lists all the shared members
and none of the instance members. For more information, see Using IntelliSense.

Fields and properties

Fields and properties represent information stored in an object. You retrieve and set their values with
assignment statements the same way you retrieve and set local variables in a procedure. The following
example retrieves the Width property and sets the ForeColor property of a Label object.

Dim warningWidth As Integer = warningLabel.Width


7

warningLabel.ForeColor = System.Drawing.Color.Red
Page
Note: that a field is also called a member variable.

Use property procedures when:

 You need to control when and how a value is set or retrieved.


 The property has a well-defined set of values that need to be validated.
 Setting the value causes some perceptible change in the object's state, such as
an IsVisible property.
 Setting the property causes changes to other internal variables or to the values of other
properties.
 A set of steps must be performed before the property can be set or retrieved.

Use fields when:

 The value is of a self-validating type. For example, an error or automatic data conversion occurs if
a value other than True or False is assigned to a Boolean variable.
 Any value in the range supported by the data type is valid. This is true of many properties of
type Single or Double.
 The property is a String data type, and there is no constraint on the size or value of the string.
 For more information, see Property Procedures.

Tip: Always keep the non-constant fields private. When you want to make it public, use a property
instead.

Methods
A method is an action that an object can perform. For example, Add is a method of
the ComboBox object that adds a new entry to a combo box. The following example demonstrates
the Start method of a Timer object.

Dim safetyTimer As New System.Windows.Forms.Timer


safetyTimer.Start()

Note: that a method is simply a procedure that is exposed by an object.

Events
An event is an action recognized by an object, such as clicking the mouse or pressing a key, and for
which you can write code to respond. Events can occur as a result of a user action or program code, or
they can be caused by the system. Code that signals an event is said to raise the event, and code that
responds to it is said to handle it.

You can also develop your own custom events to be raised by your objects and handled by other
objects. For more information, see Events.

Instance members and shared members


8

When you create an object from a class, the result is an instance of that class. Members that are not
Page

declared with the Shared keyword are instance members, which belong strictly to that particular
instance. An instance member in one instance is independent of the same member in another instance
of the same class. An instance member variable, for example, can have different values in different
instances.

Members declared with the Shared keyword are shared members, which belong to the class as a whole
and not to any particular instance. A shared member exists only once, no matter how many instances of
its class you create, or even if you create no instances. A shared member variable, for example, has only
one value, which is available to all code that can access the class.

Accessing non-shared members

 Make sure the object has been created from its class and assigned to an object variable.

Dim secondForm As New System.Windows.Forms.Form

 In the statement that accesses the member, follow the object variable name with
the member-access operator (.) and then the member name.

secondForm.Show()

Accessing shared members

 Follow the class name with the member-access operator (.) and then the member name. You
should always access a Shared member of the object directly through the class name.

Console.WriteLine("This computer is called " & Environment.MachineName)

 If you have already created an object from the class, you can alternatively access
a Shared member through the object's variable.

Differences between classes and modules


The main difference between classes and modules is that classes can be instantiated as objects while
standard modules cannot. Because there is only one copy of a standard module's data, when one part of
your program changes a public variable in a standard module, any other part of the program gets the
same value if it then reads that variable. In contrast, object data exists separately for each instantiated
object. Another difference is that unlike standard modules, classes can implement interfaces. If a class is
marked with the MustInherit modifier, it can't be instantiated directly. However, it's still different from a
module as it can be inherited while modules can't be inherited.

Note

When the Shared modifier is applied to a class member, it is associated with the class itself instead of a
particular instance of the class. The member is accessed directly by using the class name, the same way
module members are accessed.
9
Page
Classes and modules also use different scopes for their members. Members defined within a class are
scoped within a specific instance of the class and exist only for the lifetime of the object. To access class
members from outside a class, you must use fully qualified names in the format of Object.Member.

On the other hand, members declared within a module are publicly accessible by default, and can be
accessed by any code that can access the module. This means that variables in a standard module are
effectively global variables because they are visible from anywhere in your project, and they exist for the
life of the program.

Reusing classes and objects


Objects let you declare variables and procedures once and then reuse them whenever needed. For
example, if you want to add a spelling checker to an application you could define all the variables and
support functions to provide spell-checking functionality. If you create your spelling checker as a class,
you can then reuse it in other applications by adding a reference to the compiled assembly. Better yet,
you may be able to save yourself some work by using a spelling checker class that someone else has
already developed.

.NET provides many examples of components that are available for use. The following example uses
the TimeZone class in the System namespace. TimeZone provides members that allow you to retrieve
information about the time zone of the current computer system.

Public Sub ExamineTimeZone()


Dim tz As System.TimeZone = System.TimeZone.CurrentTimeZone
Dim s As String = "Current time zone is "
s &= CStr(tz.GetUtcOffset(Now).Hours) & " hours and "
s &= CStr(tz.GetUtcOffset(Now).Minutes) & " minutes "
s &= "different from UTC (coordinated universal time)"
s &= vbCrLf & "and is currently "
If tz.IsDaylightSavingTime(Now) = False Then s &= "not "
s &= "on ""summer time""."
Console.WriteLine(s)
End Sub

In the preceding example, the first Dim Statement declares an object variable of type TimeZone and
assigns to it a TimeZone object returned by the CurrentTimeZone property.

Relationships among objects


Objects can be related to each other in several ways. The principal kinds of relationship
are hierarchical and containment.

Hierarchical relationship
When classes are derived from more fundamental classes, they are said to have a hierarchical
relationship. Class hierarchies are useful when describing items that are a subtype of a more general
10

class.
Page
In the following example, suppose you want to define a special kind of Button that acts like a
normal Button but also exposes a method that reverses the foreground and background colors.

Define a class that is derived from an already existing class

 Use a Class Statement to define a class from which to create the object you need.

Public Class ReversibleButton

Be sure an End Class statement follows the last line of code in your class. By default, the
integrated development environment (IDE) automatically generates an End Class when you
enter a Class statement.

 Follow the Class statement immediately with an Inherits Statement. Specify the class from which
your new class derives.

Inherits System.Windows.Forms.Button

Your new class inherits all the members defined by the base class.

 Add the code for the additional members your derived class exposes. For example, you might
add a ReverseColors method, and your derived class might look as follows:

Public Class ReversibleButton


Inherits System.Windows.Forms.Button
Public Sub ReverseColors()
Dim saveColor As System.Drawing.Color = Me.BackColor
Me.BackColor = Me.ForeColor
Me.ForeColor = saveColor
End Sub
End Class

If you create an object from the ReversibleButton class, it can access all the members of
the Button class, as well as the ReverseColors method and any other new members you define
in ReversibleButton.

Derived classes inherit members from the class they are based on, allowing you to add complexity as
you progress in a class hierarchy. For more information, see Inheritance Basics.

Compile the code


Be sure the compiler can access the class from which you intend to derive your new class. This might
mean fully qualifying its name, as in the preceding example, or identifying its namespace in an Imports
Statement (.NET Namespace and Type). If the class is in a different project, you might need to add a
11

reference to that project. For more information, see Managing references in a project.
Page
Containment relationship
Another way that objects can be related is a containment relationship. Container objects logically
encapsulate other objects. For example, the OperatingSystem object logically contains
a Version object, which it returns through its Version property. Note that the container object does not
physically contain any other object.

Collections
One particular type of object containment is represented by collections. Collections are groups of similar
objects that can be enumerated. Visual Basic supports a specific syntax in the “For Each...Next
Statement” that allows you to iterate through the items of a collection. Additionally, collections often
allow you to use an Item[] to retrieve elements by their index or by associating them with a unique
string. Collections can be easier to use than arrays because they allow you to add or remove items
without using indexes. Because of their ease of use, collections are often used to store forms and
controls.

Lesson 4 - Constructors
Constructor is a method and it will invoke automatically whenever an instance of class or struct is
created. The constructor is useful to initialize and set default values for the data members of the new object.
In case, if we create a class without having any constructor, the compiler will automatically create a one
default constructor for that class. So, there is always one constructor that will exist in every class.

Constructor Syntax
As discussed, the constructor is a method and it won’t contain any return type. If we want to create a
constructor in visual basic, we need to create a method with New keyword.

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

If you observe the above syntax, we created a class called “User” and a method with New keyword. Here
the method New() will become a constructor of our class.

Constructor Types
In visual basic, we have a different type of constructors available, those are
12

 Default Constructor
 Parameterized Constructor
Page

 Copy Constructor
 Private Constructor

Default Constructor
In visual basic, if we create a constructor without having any parameters, we will call it as default
constructor and the instance of the class will be initialized without any parameter values.

Following is the example of defining the default constructor in visual basic programming language.

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()
' The constructor will be called automatically once the instance o
f the class created
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

If you observe the above example, we created a class called “User” and the constructor method “New()”
without having any parameters. When we create an instance of our class (User), then automatically our
constructor method will be called.

When we execute the above visual basic program, we will get the result as shown below.

If you observe the above result, our constructor method


has called automatically and initialized the parameter
values after creating an instance of our class.

Parameterized Constructor
In visual basic, if we create a constructor with at least one parameter, we will call it a parameterized
constructor and every time the instance of the class must be initialized with parameter values. Following
13

is the example of defining the parameterized constructor in a visual basic programming language.
Page

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 o
f 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

If you observe the above example, we created a class called “User” and the constructor method
“New(string, string)” with parameters. When we create an instance of our class (User) with required
parameters, then automatically our constructor method will be called.

When we execute the above visual basic program, we will get the result as shown below.

If you observe the above result, our constructor method


has called automatically and initialized the parameter
values after creating an instance of our class with the
required parameters.

Copy Constructor

In visual basic, Copy Constructor is a parameterized constructor that contains a parameter of the same
class type. The copy constructor in visual basic is useful whenever we want to initialize a new instance to
the values of an existing instance.

In simple words, we can say copy constructor is a constructor which copies the data of one object into
another object. Generally, visual basic won’t provide a copy constructor for objects but we can implement
ourselves based on our requirements.

Copy Constructor Syntax

Following is the syntax of defining a copy constructor in visual basic programming language.

Class User
' Parameterized Constructor
14

Public Sub New(ByVal a As String, ByVal b As String)


' your code
Page

End Sub
' Copy Constructor
Public Sub New(ByVal user As User)
' your code
End Sub
End Class

If you observe the above syntax, we created a copy constructor with a parameter of the same class type
and it helps us to initialize a new instance to the values of an existing instance. Following is the example
of creating a copy constructor to initialize a new instance to the values of an existing instance in visual
basic programming language.
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
' Copy Constructor
Public Sub New(ByVal user As User)
name = user.name
location = user.location
End Sub
End Class
Sub Main()
' User object with Parameterized constructor
Dim user As User = New User("Suresh Dasari", "Hyderabad")
' Another User object (user1) by copying user details
Dim user1 As User = New User(user)
user1.name = "Rohini Alavala"
user1.location = "Guntur"
Console.WriteLine(user.name & ", " & user.location)
Console.WriteLine(user1.name & ", " & user1.location)
Console.WriteLine("Press Enter Key to Exit..")
Console.ReadLine()
End Sub
End Module

If you observe the above example, we created an instance of copy constructor (user1) and using an
instance of the user object as a parameter type. So, the properties of user object will be sent
to user1 object and we are changing the property values of user1 object but those will not effect
the user object property values.

When we execute the above visual basic program, we will get the result as shown below.

If you observe the above result, we initialized a


new instance to the values of an existing instance
but those changes not effected the existing
instance values.
15
Page
This is how we can use copy constructor in a visual basic programming language to create a constructor
with the parameter of the same class type based on our requirements.
Private Constructor

In visual basic, Private Constructor is a special instance constructor and it is useful in classes that contain
only static members. If a class contains one or more private constructors and no public constructors, then
the other classes are not allowed to create an instance for that particular class except nested classes.

Private Constructor Syntax

Following is the syntax of defining a private constructor in a visual basic programming language.

Class User
' Private Constructor
Private Sub New()
' Custom Code
End Sub
End Class

If you observe the above syntax, we created a private constructor without having any parameters that mean
it will prevent an automatic generation of default constructor. In case, if we didn’t use any access modifier
to define constructor, then by default it will treat it as a private. Following is the example of creating a private
constructor in a visual basic programming language to prevent other classes to create an instance of a
particular class.

Module Module1
Class User
' Private Constructor
Private Sub New()
Console.WriteLine("I am Private Constructor")
End Sub
Public Shared name, location As String
' Default Constructor
Public Sub New(ByVal a As String, ByVal b As String)
name = a
location = b
End Sub
End Class
Sub Main()
' The following comment line will throw an error because constructor
is inaccessible
' Dim user As User = New User()

' Only Default constructor with parameters will invoke


Dim user1 As User = New User("Suresh Dasari", "Hyderabad")
Console.WriteLine(User.name & ", " & User.location)
Console.WriteLine("Press Enter Key to Exit..")
Console.ReadLine()
End Sub
End Module
16
Page
If you observe the above example, we created a class with a private constructor and default
constructor with parameters. If we uncomment the commented line (Dim user1 As User = New User()), it
will throw an error because the constructor is private so it won’t allow you to create an instance for that
class.

Here, we are accessing the class properties directly with a class name because those are static properties
so it won’t allow you to access with instance name.

When we execute above the visual basic program, we will get the result as shown below.

This is how we can use a private constructor in a visual basic


programming language to prevent creating an instance of a
particular class based on our requirements.

Declare an Object by Using an Object Initializer


Object initializers enable you to declare and instantiate an instance of a class in a single statement. In
addition, you can initialize one or more members of the instance at the same time, without invoking a
parameterized constructor.

When you use an object initializer to create an instance of a named type, the parameter less constructor
for the class is called, followed by initialization of designated members in the order you specify.

The following procedure shows how to create an instance of a Student class in three different ways. The
class has first name, last name, and class year properties, among others. Each of the three declarations
creates a new instance of Student, with property First set to "Michael", property Last set to "Tucker", and
all other members set to their default values. The result of each declaration in the procedure is equivalent
to the following example, which does not use an object initializer.

Dim student0 As New Student


With student0
.First = "Michael"
.Last = "Tucker"
End With

Lesson 5 Crore Principles of Object Oriented Programing


Encapsulation

Encapsulation is the exposure of properties and methods of an object while hiding the actual
17

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.
Page
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. Let’s take a look at examples of a Person class.

Example 1: Person Class Implementation

Public Class Person


Private m_sFirstName as String
Private m_sLastName as String
Public Property FirstName() as String
Get
FirstName = m_sFirstName
End Get
Set(ByVal Value as String)
m_sFirstName = Value
End Set
End Property

Public Property LastName() as String


Get
LastName = m_sLastName
End Get
Set(ByVal Value as String)
m_sLastName = Value
End Set
End Property
ReadOnly Property FullName() as String
Get
FullName = m_sLastName & ", " & m_sFirstName
End Get
End Property
End Class

This illustrates how the internal implementation of the classes is different but the external interface
encapsulates how the class works internally. That is the goal of encapsulation: to allow a developer to
transparently use different implementations of the same object.

Polymorphism

Polymorphism is the concept that different objects have different implementations of the same
characteristic. For example, consider two objects, one representing a Porsche 911 and the other a
18

Toyota Corolla. They are both cars; that is, they both derive from the Car class, and they both have a
Page

drive method, but the implementations of the methods could be drastically different.
Polymorphism sounds a great deal like encapsulation, but it is different. Encapsulation has to do with
hiding the internal implementation of an object. Polymorphism has to do with multiple classes having
the same interface.

Visual Basic introduced a very limited support for polymorphism in VB 4.0 through the use of late
binding. Late binding is the technology for code to determine at runtime what properties and methods a
given object provides. This allows code to create any object and attempt to call a method or property of
that object without knowing whether the object supports the method at compile time. Given two
different classes with the same properties and methods, a variable of type object could be used to
instantiate an object of either class. This worked, but did not provide any type safety at compile time.
Type safety is the concept to ensure that a string is used as a string, an integer is used as an integer, and
a Boolean is used as a Boolean. Without type safety, potentially more errors can occur when a user is
executing a program rather than when the program is compiled. Type safety also is one mechanism to
prevent hackers from overloading code with a destructive piece of code.

VB 5 introduced an additional form of polymorphism using interfaces. An interface defines a set of


properties, methods, and events that a class implements. Any number of classes can implement the
same interface. A variable that instantiates an interface can reference any class that implements that
interface.

Interfaces provide early binding to an object, which can greatly improve performance and also provide
type protection at compile time. Interfaces were the most important feature introduced in VB 5, but are
still one of the least understood or used.

As you'll see later in this chapter, VB.NET has improved support for interfaces. The language now has
direct support for interfaces creation, which was done in earlier versions either via IDL or by creating
empty classes. In addition, a single method can be the implementation of methods in multiple
interfaces.
Example 2 illustrates polymorphism through late binding and Example 3 illustrates polymorphism
through early binding. Both listings show classes that implement Ride methods. As shown, whether
using either late binding or early binding, a method can call either class's method without caring what
kind of object it is using. This is the essence of polymorphism: It provides the ability to create code that
can use different objects that implement the same interfaces.

Example 2: Polymorphism Through Late Binding


19

Public Class RollerCoaster


Page

Public Sub Ride()


Console.WriteLine("Here we go")
Console.WriteLine("Click, Click ,Click")
Console.WriteLine("Oh, *&@&#%")
Console.WriteLine("That was great")
End Sub
End Class
Public Class MerryGoRound
Public Sub Ride()
Console.WriteLine("OK will go on it")
Console.Writeline("Nap Time")
Console.WriteLine("Yea its over")
End Sub
End Class
‘Some code somewhere else in the application:

Private Sub DayAtTheAmusementPark()


Dim oRollerCoaster as New RollerCoaster
Dim oMerryGoRound as New MerryGoRound
Call GoOnRide(oRollerCoaster)
Call GoOnRide(oMerryGoRound)
End Sub
Private Sub GoOnRide(oRide as Object)
oRide.Ride()
End Sub

For better performance and to find errors at compile time, early binding is the preferred choice. Early
binding can be accomplished through the use of Interfaces

Example 3: Polymorphism Through Interfaces


Public Interface IAmusementParkRide
Sub Ride()
End Interface

Public Class RollerCoaster


Implements IAmusementParkRide
Public Sub IAmusementParkRide_Ride()
Console.WriteLine("Here we go")
Console.WriteLine("Click, Click ,Click")
Console.WriteLine("Oh, *&@&#%")
Console.WriteLine("That was great")
End Sub
End Class

Public Class MerryGoRound


Implements IAmusementParkRide
Public Sub IAmusementParkRide_Ride()
Console.WriteLine("OK will go on it")
Console.Writeline("Nap Time")
Console.WriteLine("Yea its over")
20

End Sub
End Class
Page

‘Some code somewhere else in the application:


Private Sub DayAtTheAmusementPark()
Dim oRollerCoaster as New RollerCoaster
Dim oMerryGoRound as New MerryGoRound
Call GoOnRide(oRollerCoaster)
Call GoOnRide(oMerryGoRound)
End Sub
Private Sub GoOnRide(oRide as IAmusementParkRide)
oRide.Ride()
End Sub

Inheritance
Inheritance is the idea that one class, called a subclass, can be based on another class, called a base
class. Inheritance provides a mechanism for creating hierarchies of objects. For example, a dog is a
mammal and a collie is a dog. Thus the dog class inherits the properties and methods of
the mammal class, and the collie class inherits from both dog and mammal.

The objects in a hierarchy have two different types of relationships to one another, referred to in object-
oriented parlance as HasA and IsA relationships. For example, a Collie IsA dog and HasA tail.
Implementation inheritance is the object-oriented feature that supports IsA relationships. Containment
supports HasA relationships. Implementation inheritance is also another way that VB.NET supports
polymorphism. A function might accept a parameter typed as mammal and then an object that is
derived from mammal can be passed in as the parameter.

Implementation Inheritance
Since version 5, Visual Basic has supported interface inheritance through the implements keyword. In
previous versions of VB, the idea of using an existing class as the starting point in the development of a
new class wasn't possible. This language feature is known as implementation inheritance. Now in
VB.NET, implementation inheritance has been added to the language.

Previous versions of Visual Basic were targeted to COM development, which discouraged the use of
implementation inheritance. Visual Basic.NET, on the other hand, is targeted for the .Net Framework,
which is based on implementation inheritance.

Support for implementation inheritance is perhaps the biggest change in Visual Basic.NET. Table 3.1
shows the new keywords that have been added along with new statements and methods.

New Language Elements for Implementation Inheritance

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 from
21

MustInherit Class Statement Indicates a class that must be inherited by another class
Page
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

MyBase Code Allows code in a class to invoke code in the base class

MyClass Code Allows code in a class to invoke code in itself

Protected Function, Sub, Field, Indicates that code in a child class can access this
Property

The example shows a number of the new keywords in action. The code describes a class with four
properties and one method. Any class that inherits from this class must override
the ClassName property. No class that inherits from this class can override
the BaseClassName property. Any class that inherits from this class can freely override the remaining
properties and methods.

Example 4: Person Class


Public Class Person
Protected c_sFirstName as String
Protected c_sLastName as String
MustOverride ReadOnly Property ClassName() as String
Get
ClassName = "Person"
End Get
End Property
NotOverridable ReadOnly Property BaseClassName() as String
Get
BaseClassName = "Person"
End Get
End Property
Overidable Public Property FirstName() as String
Get
22

FirstName = c_sFirstName
End Get
Page

Set(ByVal Value as string)


c_sFirstName = Value
End Set
End Property
Overidable Public Property LastName() as String
Get
LastName = c_sLastName
End Get
Set(ByVal Value as string)
c_sLastName = Value
End Set
End Property
Overridable Sub Speak()
Console.WriteLine("I am " & c_sFirstName & " " & c_sLastName)
Console.WriteLine(" and I am a Person.")
End Sub
End Class
This example illustrates VB.NET's implementation of inheritance. In keeping with the language's
design goals, VB requires that everything be very explicit. Table 3.2 compares some of the VB.NET
keywords used to control the accessibility of classes and class members with their C# equivalents.
In my opinion, the VB.NET keywords are much clearer than the C# keywords.

Table 3.2 VB Keywords Compared to C# Keywords


VB.NET C#

NotInheritable Sealed

MustInherit Abstract

MustOverride Virtual

Inherits :

Example 5: NewPerson Class


Public Class NewPerson
Inherits Person
MustOverride Overrides Public ReadOnly Property ClassName() as String
Get
ClassName = "NewPerson"
End Get
End Property
Overrides Sub Speak()
Console.WriteLine("My name is " & c_sFirstName & " c_sLastName)
Console.WriteLine(" and I am a new person.")
23

End Sub
End Public
Page
This class shows a number of new keywords in use. Inherits indicates the class inherited.
The ClassName property accessibility is set to MustOverride and Public, indicating that any class
that inherits from this class must override this property. The Overrides keyword indicates that
the ClassName property and the Speak method from the base class are being overridden by the new
class.
Containment

Containment, as we saw earlier, is the mechanism for implementing HasA relationships. Containment is
actually rather simple, and isn't supported by anything specific within a language. In VB, for one object
to have a HasA relationship to another, the first object will simply hold an instance of a object. For
example, in my Person class, if I wanted to define a HasA relationship to the person's dog, I would
simply add the code shown in Example 6.

Example 6: Containment Illustrates HasA Relationships

Private c_oDog as Dog


Public Property MyDog() as Dog
Get
MyDog = c_oDog
End Get
End Property
Public Sub GetADog(ByVal Breed as String, ByVal Name as String)
c_oDog = New Dog(Breed,Name)

End Sub

24
Page

You might also like