Oops
Oops
Oops
Agenda
OOPs Chapter-4
1. Learning about Class, Object, Component, Encapsulation, Inheritance, Polymorphism & Object Creation and Instantiation 2. Understanding OOPs concept through an example. Table of Contents O VERVIEW W ORKING WITH M ETHODS W ORKING WITH O BJECT P ROPERTIES C ONSTRUCTORS AND D ESTRUCTORS D ESTRUCTOR W ORKING WITH STATIC M EMBERS 2 8 10 14 16 17
OOPs Chapter-4
Overview
Class:
A
class
is
a
template
/
skeleton
/
blueprint
for
creating
an
object.
Object:
An
Object
is
an
entity
that
has
properties
for
validations,
methods
for
functionality
and
events
for
depicting
the
change
of
state.
Every
object
has
the
data
and
behavior
with
which
they
are
differed.
Data
associated
at
any
given
instance
of
time
is
the
state
of
an
object.
Component:
A
ready
to
use
third
party
object
can
be
called
as
a
Component.
It
can
be
replaced
without
any
changes
in
the
application.
A
component
is
generally
used
by
a
programmer
as
an
object.
An
application
can
be
called
as
a
collection
of
related
objects
exchanging
messages
with
each
other.
Loosely
coupled
objects
are
better
than
tightly
coupled
objects
i.e.
the
lesser
the
information
given
to
other
objects
the
better
it
is
as
the
objects
are
loosely
coupled
the
dependencies
are
less
and
stronger
security.
Every
object
oriented
language
should
have
three
features:
Encapsulation
Inheritance
Polymorphism
Encapsulation: Binding of data and behavior i.e. functionality of an object within a secured and controlled environment is encapsulation. Inheritance: The Process of acquiring the existing functionality of the parent and with new added features and functionality by a child object is called inheritance. The advantages of inheritance are Generalization, Extensibility and Reusability. For example: A calculator is a generalized form of mathematical operations where as a Scientific calculator is an Extended and Specific form. Polymorphism: An object in different forms and in each form it exhibits the same functionality but implemented in different ways. For example: A man who knows more than one language can speak any language he knows. Here the functionality is speech and person is the object. A faculty can take a form of Java Faculty or MSNET faculty and in both the forms he teaches, but what he teaches differs. Here functionality is to teach and faculty is the object.
OOPs Chapter-4
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. 3. View Solution Explorer, Right Click on Project Add Class and name it as Account 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 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
OOPs Chapter-4
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. 4. Account a; 'Declaration a1 = new Account(); 'Initialization In the Account Application, Change the name of the Form, Form1 to AccountForm and design the following GUI 5. 6. Fig: 4.1 For every control on the form set Text and Name properties. In Design View, double click on every button to generate event handlers in Code View of the Form
OOPs Chapter-4
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; public Form1() { InitializeComponent(); } 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) { 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;
OOPs Chapter-4
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 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
OOPs Chapter-4
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
OOPs Chapter-4
OOPs Chapter-4
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 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
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#
OOPs Chapter-4
Edit the code in the Account Class as below: 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
10
OOPs Chapter-4
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 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 Adding properties private int _Id; private String _Name; private Decimal _Balance; public decimal Balance { get { return _Balance; } } public String Name { get { return _Name;
11
OOPs Chapter-4
11.
} 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) { if (this.Balance - amount < 500) throw new ApplicationException("Insufficient Balance"); else this._Balance -= amount; } Code: 4.5 C# 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 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
OOPs Chapter-4
13
OOPs Chapter-4
14
OOPs Chapter-4
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 Dim initialBalance As Decimal = Decimal.Parse(txtBalance.Text) Dim a As New Account(id, name, initialBalance) End Sub Code: 4.8 VB 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# Note: Once the above code is changed in Account Form, btnSet_Click is no more useful and thus it can be removed.
15
OOPs Chapter-4
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().
16
OOPs Chapter-4
17
OOPs Chapter-4
} 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: 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:
18
OOPs Chapter-4
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: 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)
19
OOPs Chapter-4
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 C# Screenshots of sequential execution of the program: 1. Run the program
20
OOPs Chapter-4
4. Click on Get
21
OOPs Chapter-4
22
OOPs Chapter-4
10. Enter MB(Minimum Balance) (1000 as shown below) and click on Set MB button.
11. Try to withdraw amount that will leave the account with less than minimum balance.
12. Error is displayed. You can click on Continue but the recent withdrawal will not be saved.
23
OOPs Chapter-4
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 only once. 1. Outside the class a static members of a class can be accessed using class name where as 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 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. 5. 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. static class Demo {
24
OOPs Chapter-4
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.
25