Overview
What is an Object?
What is not an Object?
What is
state of an Object?
What is the
Lifecycle of an Object?
How will you
distinguish two Objects?
What is the
relationship between Class and Object?
Define
Application using Objects?
Principles of Object Orientation
Encapsulation
Inheritance
Polymorphism
Encapsulation
is binding of State and Behavior together
Inheritance is based on “is a” relationship.
Understanding
Polymorphism with Examples.
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 teach and
faculty is the object.
Object
Creation and Instantiation 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.
Agenda:
1.
Write a class and add field members to the class
2.
Create an Object of the Class and understand the difference between object and
reference.
3.
Access the members of the object
4.
Copy the reference in another reference variable.
5.
Abandoning the object.
6.
Working with Methods
7.
Working with Properties
8.
Constructor & Destructor.
9. Working with “static” Members
Working
with Classes & Objects:
Account
Example
Step 1: Create a new project (File à New
Project). Name: AccountApplication,
Project Type: C#, Template: Windows Application
Step 2: View à
Solution Explorer, Right
Click on Project à Add à
Class and name it as Account
Step 3: Add to class the following code.
Code in
C#:
class Account
{
public int Id;
public String Name;
public Decimal Balance;
public Account()
{
MessageBox.Show(“Object Created”);
}
~Account()
{
MessageBox.Show(“Object Destroyed”);
}
}
Explanation: Account a; “a”
is a refrence 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
datatype.
The value of the reference variable is reference to an object on heap.
Account a; 'Declaration a1 = new Account();
'Initialization
Step 4: In the AccountApplication, Change the
name of the Form, “Form1” to “AccountForm” and design the
following GUI
Step 5: For every control on the form set
Text and Name properties.
Step 6: In DesignView, doubleclick on every
button to generate event handlers in Code View of the Form
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.
Step 7: Add the following code to the AccountForm i.e Handle all the buttons
Click event (Double click on button in design view)
Account Form Code in C#:
public partial class AccountForm: Form
{
Account a;
private void btnCreate_Click(...)
{
a = new Account();
}
private void btnGet_Click(...)
{
txtId.Text =
a.Id.ToString();
txtName.Text = a.Name;
txtBalance.Text = a.Balance.ToString();
}
private void btnClear_Click(...)
{
txtId.Text =
"";
txtName.Text = "";
txtBalance.Text =
"";
}
private void btnSet_Click(...)
{
a.Id = int.Parse(txtId.Text);
a.Name = txtName.Text;
a.Balance =
double.Parse(txtBalance.Text);
}
private void btnDestroy_Click(...)
{
a = null;
}
private void btnClear_Click(...)
{
txtId.Text =
"";
txtName.Text = "";
txtBalance.Text =
"";
}
private void btnSet_Click(...)
{
a.Id = int.Parse(txtId.Text);
a.Name = txtName.Text;
a.Balance = double.Parse(txtBalance.Text);
}
private void btnDestroy_Click(...)
{
a = null;
}
private void btnGC_Click(...)
{
GC.Collect();
}
private void btntemp_Click(...)
{
Account a1 = new
Account();
a = a1;
}
private void btnGetGeneration_Click(...)
{
MessageBox.Show(GC.GetGeneration(a).ToString());
}
}
Working with Methods
The methods
of the object are used to describe the functionality / behavior.
Notes:
1. An instance method of a class is always invoked using a
reference to an object.
2. While writing a method in a class do not set to it any
data as parameter or return type, anything which is already the data
member in the same class.
3. In a method “ “this”(CS) is reference to the current
object on which the method is invoked.
4. 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 accessed in such a method then “this” (CS) can be used.
5. The class should be always programmed in such a way that, it‟s
not specific to any particular type of application so that the same class can
reused in different applications / environment. For example, don‟t use in class
functionality like MsgBox or Console.WriteLine or Button or Label or TextBox
etc….
6. Whenever
any of the business rules of an object or the integrity of the property or a
method is violated, it should respond by throwing a runtime exception. For
example in the above method Withdraw( ) we are checking for balance to
be a minimum of 500, if violated an exception is raised.
Recommendation: A method name should start with uppercase and parameters
should use camel notation. Step 8: In the Account Class add the
following deposit and withdraw method.
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
}
Step 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.
pivate void btnDeposit_Click(
. . . )
{ a.Deposit(decimal.Parse(txtAmount.Text));
}
private void btnWithraw_Click(
. . . )
{ a.Withdraw(decimal.Parse(txtAmount.Text));
}
Working with Object Properties
1. 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 put over it.
2. 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.
3. A property procedure doesn‟t hold any data by itself instead it
depends on some private field member of the class.
4. 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.
5. Using a property the field member can be restricted with either
“ReadOnly” or “WriteOnly” access.
6. 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; }
}
|
Step 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.
private int
_Id
private
string _Name
private decimal
_Balance
public
decimal Balance
{
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; }
}
Step 11: In btnSet_Click of AccountForm please replace
a.Balance = Decimal.Parse(txtBalance.text) with a.Deposit(decimal.Parse(txtBalance.Text))
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 doesn‟t 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 doesn’t 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>()
{ //default
constructor }
<Class name>(<datatype> p1, …) { //parameterized
constructor }
<Class name>(<Class Name>
<parname>) : this(. . .) { //copy constructor }
Step 12: Add the Following code to the Account Class
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)
{ //this.Id = a.Id; //this.Name =
a.Name; //this._Balance = a.Balance; }
Step 13: In AccountForm
make the following Changes:
private void btnCreate_Click(.
. .) Handles btnCreate.Click
{
int id = int.Parse(txtId.Text);
string name = txtName.Text;
decimal initialBalance = decimal.Parse(txtBalance.Text);
a = New
Account(id,name, initialBalance);
}
Note: Once the above code is changed in AccountForm, btnSet_Click is no more
useful and thus it can be removed
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 don‟t
have Garbage collector)
In .NET, all the dependent
objects are automatically ready for Garbage Collection when the main object
doesn‟t have any references thus the destructor here doesn‟t have same
significance as in C++.
Syntax in C#: Note: A destructor in C# cannot have any access modifiers
~<class name>() { }.
Because its
not predictable when the Destructor method is going to be executed, its 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().
Working with “static”
Members
For every new instance of a
class all the instance members are allocated memory, 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.
Note: 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.
Note: 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.
Instance members are loaded and allocated memory.
5. Instance constructor is
executed.
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.
Code
in C#:
Step 14:
public static int MinBalance
= 500;
Step 17:
public static int
_PrevId
private
int Id;
Step
18: public Account()
{
_PrevId += 1; _Id = _PrevId; }
Step 19: Id is now changed to ReadOnly
Property
public
int Id { get { return _Id } }
Step 15: In
Withdraw method replace the constant value 500 with the static member "MinBalance"
Step 16: In Form: Add btnGetMB and btnSetMB buttons and txtMB textbox
with the following code.
private
void btnGetMB_Click(...) { txtMB.Text = Account.MinBalance.ToString();
}
|
Private
Sub btnSetMB_Click(...) { Account.MinBalance =
Decimal.Parse(txtMB.Text); }
|
Step 20: Because “Id” is now auto increment field, remove the id parameter from
the constructor of Account Class
Step 21: Remove “id” argument while creating the Account object in btnCreate_Click
of AccountForm
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 { public static int P1; public static void
Foo() { } }
No comments:
Post a Comment