You are on page 1of 20

Deccansoft Software Services - MS.

NET OOPs Programming Encapsulation

Agenda

1. Understanding Encapsulation concept through an example.

Table of Contents

UNDERSTANDING AND PROGRAMMING CLASSES AND OBJECTS ERROR! BOOKMARK NOT DEFINED.
WORKING WITH METHODS 7
WORKING WITH OBJECT PROPERTIES 9
CONSTRUCTORS AND DESTRUCTORS 13
DESTRUCTOR 15
WORKING WITH STATIC MEMBERS 16

1
Deccansoft Software Services - MS.NET OOPs Programming Encapsulation

Understanding and Programming Classes and Objects


In MS.NET when an object is created there is no way to get the address of an object. Only the reference to the object
is given through which we can access the members of the class for a given object. When an object is created all the
variables (value/ reference types) are allocated the memory in heap as a single unit and default values are set to
them based on their data types.
Account Example:
Steps to create an Account Application:
1. Create a new project (File New Project). Name: Account Application, Project Type: C#, Template: Windows
Application
2. View Solution Explorer, Right Click on Project Add Class and name it as Account
3. To class, add the following code:
Creating Account Class
using System;
using System.Text;
using System.Windows.Forms;
namespace AccountApplication
{
class Account
{
public int Id;
public String Name;
public Decimal Balance;
public Account()
{
MessageBox.Show("Object Created");
}
~Account()
{
MessageBox.Show("Object Destroyed");
}
}
}
Code: 4.1 C#

Creating Account Class


Public Class Account
Public Id As Integer
Public Name As String

2
Deccansoft Software Services - MS.NET OOPs Programming Encapsulation

Public Balance As Decimal


Shared Sub New()
MessageBox.Show("Object Created")
End Sub
Protected Overrides Sub Finalize()
MessageBox.Show("Object Destroyed")
End Sub
End Class
Code: 4.1 VB
Explanation:
Account a;
a is a reference variable of type Account.

Note: a is not an object of type Account.

a = new Account();
Creates an object of type Account (allocating memory on heap to every member of the Account class) and its
reference is assigned to a.
Every member allocated memory is set to its default value based on the data type.
The value of the reference variable is reference to an object on heap.
o Account a; //Declaration
o a1 = new Account(); //Initialization
4. In the Account Application, change the name of the Form, Form1 to AccountForm and design the following
GUI
5. For every control on the form set Text and Name properties.
6. In Design View, double click on every button to generate event handlers in Code View of the Form

3
Deccansoft Software Services - MS.NET OOPs Programming Encapsulation

Explanation
a.Id = 1;
The above statement can be read as: Id menber of an object of type Account referenced by a is set to 1.
Note: If a reference variable is not intialized i.e referring to null, then trying to access any member using it will throw
a runtime exception i.e. NullReferenceException.
Account a1;
a1 = a; //Copies the value of a (reference to the object) into a1 and thus both a1 and a refers to the same object.
Note: One Object can have many references but one reference variable cannot refer to many objects.

7. Add the following code to the Account Form i.e. Handle all the buttons Click event (Double click on button in
design view)
Account Form Code
using System;
using System.Text;
using System.Windows.Forms;
namespace AccountApplication
{
public partial class AccountForm : Form
{
Account a;
private void btnCreate_Click(object sender, EventArgs e)
{
a = new Account();
}
private void btnGet_Click(object sender, EventArgs e)
{
txtId.Text = a.Id.ToString();
txtName.Text = a.Name;
txtBalance.Text = a.Balance.ToString();
}
private void btnClear_Click(object sender, EventArgs e)
{
txtId.Text = "";
txtName.Text = "";
txtBalance.Text = "";
}
private void btnSet_Click(object sender, EventArgs e)
{

4
Deccansoft Software Services - MS.NET OOPs Programming Encapsulation

a.Id = int.Parse(txtId.Text);
a.Name = txtName.Text;
a.Balance = decimal.Parse(txtBalance.Text);
}
private void btnDestroy_Click(object sender, EventArgs e)
{
a = null;
}
private void btnGC_Click(object sender, EventArgs e)
{
GC.Collect();
}
private void btnTemp_Click(object sender, EventArgs e)
{
Account a1 = new Account();
a = a1;
}
private void btnGetgeneration_Click(object sender, EventArgs e)
{
MessageBox.Show(GC.GetGeneration(a).ToString());
}
}
}
Code: 4.2 C#

Account Form Code


Public Class AccountForm
Dim a As Account
Private Sub btnCreate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
btnCreate.Click
Dim a As New Account
End Sub
Private Sub btnGet_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
btnGet.Click
txtId.Text = a.Id.ToString()
txtName.Text = a.Name
txtBalance.Text = a.Balance.ToString()
End Sub

5
Deccansoft Software Services - MS.NET OOPs Programming Encapsulation

Private Sub btnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


btnClear.Click
txtId.Text = ""
txtName.Text = ""
txtBalance.Text = ""
End Sub
Private Sub btnSet_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
btnSet.Click
a.Id = Integer.Parse(txtId.Text)
a.Name = txtName.Text
a.Balance = Decimal.Parse(txtBalance.Text)
End Sub
Private Sub btnDestroy_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
btnDestroy.Click
a = Nothing
End Sub
Private Sub btnGC_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
btnGC.Click
GC.Collect()
End Sub
Private Sub btnTemp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
btnTemp.Click
Dim a1 As New Account
a = a1
End Sub
Private Sub btnGetGeneration_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles btnGetGeneration.Click
MessageBox.Show(GC.GetGeneration(a).ToString())
End Sub
End Class
Code: 4.2 VB

6
Deccansoft Software Services - MS.NET OOPs Programming Encapsulation

Working with Methods in Classes


The methods of the object are used to describe the functionality / behavior.

Note:
An instance method of a class is always invoked only using a reference to an object. Thus it has access to
all the data which is encapsulated by an object of that class.
A method requires parameters only for that data which it doesnt have direct access to but is needed for
implementation of logic. Thus while writing a method in a class if that data is already the data member in
the same class do not set to it any data as parameter or return type.
Inside a method this is reference to the current object on which the method is invoked.
If parameter/local variable and data member of a class have same name, the local variable takes the
precedence over data member and if data member has to be accessed then this should be used to
resolve name ambiguity.
Whenever any of the business rules of an object or the integrity of the object is violated through a
property or a method, it should respond by throwing a runtime exception.
The class should be always programmed in such a way that, its not specific to any particular type of
application (Windows/Console/ClassLibrary/Service) so that the same class can reused in different
applications / environment. For example, dont use in class functionality like MessageBox or
Console.WriteLine or Button or Label or TextBox etc.
8. In the Account Class add the following deposit and withdraw method.

Adding Deposit and Withdraw methods


public void Deposit(decimal amount)
{
this.Balance += amount;
}
public void Withdraw(decimal amount)
{
if (this.Balance - amount < 500)
throw new ApplicationException("Insufficient Balance");
else
this.Balance -= amount;
}
Code: 4.3 C#

Adding Deposit and Withdraw methods


Public Sub Deposit(ByVal amount As Decimal)
Me.Balance += amount
End Sub

7
Deccansoft Software Services - MS.NET OOPs Programming Encapsulation

Public Sub Withdraw(ByVal amount As Decimal)


If Me.Balance - amount < 500 Then
Throw New ApplicationException("Insufficient Balance")
Else
Me.Balance -= amount
End If
End Sub
Code: 4.3 VB

9. Add Deposit (btnDeposit) and Withdraw (btnWithdraw) buttons and Amount (txtAmount) textbox to the
AccountForm. Add the following code to the event handler of the btnDeposit and btnWithdraw.
Handling Withdraw and Deposit events
private void btnDeposit_Click(object sender, EventArgs e)
{
a.Deposit(decimal.Parse(txtAmount.Text));
}
private void btnWithdraw_Click(object sender, EventArgs e)
{
a.Withdraw(decimal.Parse(txtAmount.Text));
}
Code: 4.4 C#

Handling Withdraw and Deposit events


Private Sub btnWithdraw_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
btnWithdraw.Click
a.Withdraw(Decimal.Parse(txtAmount.Text))
End Sub

Private Sub btnDeposit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles


btnDeposit.Click
a.Deposit(Decimal.Parse(txtAmount.Text))
End Sub
Code: 4.4 VB

8
Deccansoft Software Services - MS.NET OOPs Programming Encapsulation

Working with Object Properties

A Property encapsulates a field member of the same class, so that the field member is not freely accessible
outside the class and the required validation/restriction can be provided on it.

A property is made of two blocks i.e. Get and Set. Get block is invoked when the property is used on RHS and
Set block is invoked when the property is used on LHS.
A property procedure doesnt hold any data by itself instead it depends on some private field member of the
class.
A Set block can validate the value before it is assigned to the field member of the class being encapsulated
by the property. Similarly the field member can be validated before its value is returned in the Get block.

Using a property the field member can be restricted with either ReadOnly or WriteOnly access.
A class which has all its field members as Private and if required restricted access to these members is given
using Public Properties is called Fully Encapsulated Class.
Syntax in C#:
Private <Datatype> _<propertyname>;
public <Datatype> <PropertyName>
{
[private] get
{
return _<propertyname>;
}
[private] set
{
_<propertyname> = value;
}
}

10. Add the properties for Name, Balance and Id with following conditions:
Balance should be ReadOnly.
Name should accept greater or equal to and 5 characters and less than or equal to 20 characters only
Id should be set only once.
Edit the code in the Account Class as below:
Adding properties
private int _Id;
private String _Name;
private Decimal _Balance;
public decimal Balance
{

9
Deccansoft Software Services - MS.NET OOPs Programming Encapsulation

get
{
return _Balance;
}
}
public String Name
{
get
{
return _Name;
}
set
{
if (value.Length > 8)
throw new ApplicationException("Name cannot be > 8 characters");
_Name = value;
}
}
private bool idAlreadySet;
public int Id
{
get
{
return _Id;
}
set
{
if (idAlreadySet)
throw new ApplicationException("Id is already set");
_Id = value;
idAlreadySet = true;
}
}
public void Deposit(decimal amount)
{
this._Balance += amount;
}
public void Withdraw(decimal amount)
{

10
Deccansoft Software Services - MS.NET OOPs Programming Encapsulation

if (this.Balance - amount < 500)


throw new ApplicationException("Insufficient Balance");
else
this._Balance -= amount;
}
Code: 4.5 C#

Adding properties
Private _Id As Integer
Private _Name As String
Private _Balance As Decimal
Private idAlreadySet As Boolean
Public Property Id As Integer
Get
Return _Id
End Get
Set(ByVal value As Integer)
If (idAlreadySet) Then
Throw New ApplicationException("Id is already set")
End If
_Id = value
idAlreadySet = True
End Set
End Property
Public Property Name As String
Get
Return _Name
End Get
Set(ByVal value As String)
If (value.Length > 8) Then
Throw New ApplicationException("Name cannot be greater than 8 characters")
End If
_Name = value
End Set
End Property
Public ReadOnly Property Balance As Decimal
Get
Return _Balance

11
Deccansoft Software Services - MS.NET OOPs Programming Encapsulation

End Get
End Property
Public Sub Deposit(ByVal amount As Decimal)
Me._Balance += amount
End Sub
Public Sub Withdraw(ByVal amount As Decimal)
If Me.Balance - amount < 500 Then
Throw New ApplicationException("Insufficient Balance")
Else
Me._Balance -= amount
End If
End Sub
Code: 4.5 VB

11. In btnSet_Click of AccountForm


replace a.Balance = Decimal.Parse(txtBalance.text)
with a.Deposit(decimal.Parse(txtBalance.Text))

To assign the values to an object


private void btnSet_Click(object sender, EventArgs e)
{
a.Id = int.Parse(txtId.Text);
a.Name = txtName.Text;
a.Deposit(decimal.Parse(txtBalance.Text));
}
Code: 4.6 C#

To assign the values to an object


Private Sub btnSet_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
btnSet.Click
a.Id = Integer.Parse(txtId.Text)
a.Name = txtName.Text
a.Deposit(Decimal.Parse(txtBalance.Text))
End Sub
Code: 4.6 VB

12
Deccansoft Software Services - MS.NET OOPs Programming Encapsulation

Constructors and Destructors


A constructor is a member method of a class which is automatically executed / called as soon as the object of that
class is created and thus it is ideally used for initializing the field members of the object.
1. A constructor has same name as the class and doesnt have a return type not even void.
2. A constructor without a parameter is called default constructor and the one with parameters is called as
Parameterized constructor.
3. If a class doesnt have any form of constructor, a public default constructor is automatically added to it by the
language compiler.
4. Copy Constructor is used to create a new object by duplicating the state of an existing object and this is done
by copying the data members of existing object in new object data members.
Syntax in C#:
<Class name>()
{
//parameterless constructor
}
<Class name>(<datatype> p1, )
{
//parameterized constructor
}
<Class name>(<Class Name> <parname>) : this(. . .)
{
//copy constructor
}

12. Add the Following code to the Account Class


Adding parameterized constructors
public Account()
{}
public Account(int id, String name, decimal balance)
: this()
{
this.Id = id;
this.Name = name;
this._Balance = balance;
}
public Account(Account a)
: this(a.Id, a.Name, a.Balance)
{

13
Deccansoft Software Services - MS.NET OOPs Programming Encapsulation

//this.Id = a.Id;
//this.Name = a.Name;
//this._Balance = a.Balance;
}
Code: 4.7 C#

Adding parameterized constructors


Public Sub New()
End Sub
Public Sub New(ByVal id As Integer, ByVal name As String, ByVal balance As Decimal)
Me.Id = id
Me.Name = name
Me._Balance = balance
End Sub
Public Sub New(ByVal a As Account)
Me.New(a.Id, a.Name, a.Balance)
'Me.Id = Id
'Me.Name = Name
'Me._Balance = Balance
End Sub
Code: 4.7 VB

13. In AccountForm make the following Changes:


Changes in click event of Create
private void btnCreate_Click(object sender, EventArgs e)
{
int id = int.Parse(txtId.Text);
string name = txtName.Text;
decimal initialBalance = decimal.Parse(txtBalance.Text);
a = new Account(id,name, initialBalance);
}
Code: 4.8 C#

Changes in click event of Create


Private Sub btnCreate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
btnCreate.Click
Dim id As Integer = Integer.Parse(txtId.Text)
Dim name As String = txtName.Text

14
Deccansoft Software Services - MS.NET OOPs Programming Encapsulation

Dim initialBalance As Decimal = Decimal.Parse(txtBalance.Text)


Dim a As New Account(id, name, initialBalance)
End Sub
Code: 4.8 VB

Note: Once the above code is changed in Account Form, btnSet_Click is no more useful and thus it can be
removed or commented

Destructor
A destructor is used to release the resources that an object is holding. When an object is ready to be destroyed
Finalize method / Destructor is called on that object.
In C++, destructor of a class is responsible for destroying all the other objects which the object of this class
has created during its lifetime. (In C++ we dont have Garbage collector)
In .NET, all the dependent objects are automatically ready for Garbage Collection when the main object
doesnt have any references thus the destructor here doesnt have same significance as in C++.

Syntax in C#:
Syntax in C#:
~<class name>()
{ }.
Note: A destructor in C# cannot have any access modifiers

Because its not predictable when the Destructor method will be executed, it is not recommended to only rely on
destructor for releasing of resources and thus Microsoft has suggested two methods that can be invoked by the
programmer for the release of resources i.e. Close() or Dispose().

15
Deccansoft Software Services - MS.NET OOPs Programming Encapsulation

Working with static Members


For every new instance of a class, all the instance members are allocated memory as one unit, but static field
members of a class are allocated memory only once irrespective of the number of objects created and they are
allocated memory when the class is loaded. These members are also called class members and are accessed outside
the class using class name.

1. A class is loaded when either the static members of the class is accessed for the first time or when the
first instance of the class is created. A class once loaded will remain in memory permanently and thus
also are all static members of that class.
2. A public static member of a class can be used as Global member of the application because it can be
assessed using class name from any part of the application.

Static Constructor: A constructor is defined with the keyword as static (in C#). It is used to initialize the static
member dynamically and is executed when the class is loaded.
This is invoked by the CLR when the class is loaded by it and hence cannot be overloaded nor can be declared with
any accesses specifier like public or private.

Series of events that occur when the first object is created:


1. Class is loaded.
2. Static members are loaded and allocated memory.
3. Static constructor is executed.
4. Object is created and Instance members are loaded and allocated memory.
5. Instance constructor is executed.
6. 4 and 5 repeat for subsequent object.

Note: Static Constructor cannot access Instance members of the class. This is because when the static
constructor is executed the instance members are not allocated any memory.

Perform the following steps sequentially


14. Create a new static variable in Account class:
public static int MinBalance = 500; //Add this in Account class

15. In Withdraw method replace the constant value 500 with the static member "MinBalance":
if (this.Balance - amount < MinBalance) //replace 500 with MinBalance

16. In Form: Add btnGetMB and btnSetMB buttons and txtMB textbox with the following code:
private void btnGetMB_Click(object sender, EventArgs e)
{
txtMB.Text = Account.MinBalance.ToString();

16
Deccansoft Software Services - MS.NET OOPs Programming Encapsulation

}
private void btnSetMB_Click(object sender, EventArgs e)
{
Account.MinBalance = int.Parse(txtMB.Text);
}
17. Create a new static variable in Account class:
public static int _PrevId;
18. Make the following changes in default constructor of Account class to autogenerate the next ID instead of
user entering a value:
public Account()
{
_PrevId += 1;
_Id = _PrevId;
}
19. Id now should be changed to a ReadOnly property as we are autogenerating the new IDs. For this we can
remove the setter as shown below:
public int Id
{
get
{
return _Id;
}
//set
//{
// if (idAlreadySet)
// throw new ApplicationException("Id is already set");
// _Id = value;
// idAlreadySet = true;
//}
}
20. Because Id is now auto increment field generate by default constructor, remove the id parameter from
parameterized constructor of Account Class:
20. Remove id member initialization while creating the Account object in btnCreate_Click of AccountForm:
21. Remove a.id argument for updating the Account object in btnSet_Click of AccountForm:
private void btnSet_Click(object sender, EventArgs e)
{
//a.Id = int.Parse(txtId.Text);
}
Code: 4.9 CS

17
Deccansoft Software Services - MS.NET OOPs Programming Encapsulation

Perform the following steps sequentially


14. Create a new Shared variable in Account class:
Public Shared MinBalance As Integer = 500 'Add this in Account class
15. In Withdraw method replace the constant value 500 with the static member "MinBalance":
If Me.Balance - amount < MinBalance Then 'replace 500 with MinBalance
16. In Form: Add btnGetMB and btnSetMB buttons and txtMB textbox with the following code:
Private Sub btnGetMB_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
btnGetMB.Click
txtMB.Text = Account.MinBalance.ToString()
End Sub
Private Sub btnSetMB_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
btnSetMB.Click
Account.MinBalance = Integer.Parse(txtMB.Text)
End Sub
17. Create a new static variable in Account class:
Public Shared _PrevId As Integer
18. Make the following changes in default constructor of Account class to autogenerate the next ID instead
of user entering a value:
Public Sub New()
_PrevId += 1
_Id = _PrevId
End Sub
19. Id now should be changed to a ReadOnly property as we are autogenerating the new IDs. For this we can
remove the setter as shown below:
Public ReadOnly Property Id As Integer 'Add ReadOnly keyword to Property definition
Get
Return _Id
End Get
'Set(ByVal value As Integer)
' If (idAlreadySet) Then
' Throw New ApplicationException("Id is already set")
' End If
' _Id = value
' idAlreadySet = True
'End Set
End Property
20. Because Id is now auto increment field generate by default constructor, remove the id parameter from
parameterized constructor of Account Class:

18
Deccansoft Software Services - MS.NET OOPs Programming Encapsulation

Public Sub New(ByVal name As String, ByVal balance As Decimal)


Me.Name = name
Me._Balance = balance
End Sub
Public Sub New(ByVal a As Account)
Me.New(a.Name, a.Balance)
End Sub
20. Remove id argument while creating the Account object in btnCreate_Click of AccountForm:
Private Sub btnCreate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles
btnCreate.Click
'Dim id As Integer = Integer.Parse(txtId.Text)
Dim name As String = txtName.Text
Dim initialBalance As Decimal = Decimal.Parse(txtBalance.Text)
Dim a As New Account(name, initialBalance) 'Removed id arguments
End Sub
21. Remove a.id argument for updating the Account object in btnSet_Click
of AccountForm:
Private Sub btnSet_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSet.Click
'a.Id = Integer.Parse(txtId.Text)
a.Name = txtName.Text
a.Deposit(Decimal.Parse(txtBalance.Text))
End Sub
Code: 4.9 VB

Static Methods:
A method which does not have anything to do with the state of the object can be marked as static method.
Eg: class File
{
public static void Copy(string srcPath, string destPath)
{...}
}

Note: All methods and properties (procedures) of the class irrespective of whether they are static or not are
allocated memory for instructions only once.
1. Outside the class a static members of a class can be accessed using class name whereas the instance member of
a class must be accessed using a reference variable referring to an object of that class.
2. Instance members of the class cannot be accessed in a static constructor or any other static method or property
of the class (unless it is qualified by a reference variable referring to an object of that class).
For Example

19
Deccansoft Software Services - MS.NET OOPs Programming Encapsulation

public static void Foo()


{
//_Balance = 100; // Is Invalid
Accout a = new Account();
a._Balance = 100; // IsValid because _Balance is qualified by a which is reference to an object.
}
3. An instance member can access static members of the class.
4. this cannot be used in the static member of a class.

Static Class:
A class in C# can be declared as static and such a class can have only static members and instance members are not
allowed. Also such a class cannot be instantiated.
It is ideally used for managing Global data.
static class Demo
{
public static int P1;
public static void Foo()
{}
}
Summary:
In this section, we have seen the tenets of object oriented programming and how one can use these in one of the
real life requirements.

20

You might also like