Professional Documents
Culture Documents
4 - OOPS - Programming Encapsulation
4 - OOPS - Programming Encapsulation
Agenda
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
2
Deccansoft Software Services - MS.NET OOPs Programming Encapsulation
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#
5
Deccansoft Software Services - MS.NET OOPs Programming Encapsulation
6
Deccansoft Software Services - MS.NET OOPs Programming Encapsulation
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.
7
Deccansoft Software Services - MS.NET OOPs Programming Encapsulation
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#
8
Deccansoft Software Services - MS.NET OOPs Programming Encapsulation
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
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
12
Deccansoft Software Services - MS.NET OOPs Programming Encapsulation
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#
14
Deccansoft Software Services - MS.NET OOPs Programming Encapsulation
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
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.
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.
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
18
Deccansoft Software Services - MS.NET OOPs Programming Encapsulation
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
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