Monday, October 3, 2011

CLASS MEMBERS


Now discussing about an eg. Of program for Case study –
public class Customer
{
int Custid;
double bal;
public Customer(int Custid)
{
this.Custid = Custid; ;
bal = <read balance from DB table for given Id >
}
public double Find Banlance()
{
return bal;
}
public void WithDrow(double amt)
{
bal -= amt;
- update bal to DB table for given Id
}
public void Deposit (double amt)
{
bal += amt;
- update bal to DB table for given Id
}
  • Assume the above class being used to perform the transactions in an ATM machine. here whenever a Clint tries to access the system basing on his customer id an object gets created and give to each customer, suppose the database contain the details of the customers as following –


Customer
Custid
Cname
Balance
101
xxx
5000
102
yyy
12000
103
zzz
15600
Now for each customer accessing the system basing on his Custid an object gets created by loading the details from DATABASE server.
Customer c1 = New Customer(101);
Customer c2 = New Customer(102);
Customer c3 = New Customer(103);
Because each customer is associate either a separate object any transaction performed by customer manipulation gets affected to that particular object data only.

c1.Deposit(3000);
c2.WithDraw(4000);
CLASS MEMBERS: - 
   As we are aware that a class is a collection of members like – variables, methods, constructors etc. these members were divided into two categories –

  1. Instance members.
  2. Static members.
The members of a class which do required object of a class for initialization or execution were referred as instance members or non-static members.
The members of a class which do not required the object of a class for initialization or execution were static members.
Static Variables VS Instance Variable
  • A variable declared using static modifier or a variable declared under a static block is static rest of all are instance only.

int x = 100; //Instance variable
static int y = 200; //static variable
static void Main()
{
int z = 300; //static variable
}

  •  A static variable gets initialized once the class starts its execution where as an instance variable gets initialized only after crating the object of the class.
  •  The minimum and maximum no of time a static variable gets initialized will be on and only one time in the execution of the class, where as in case of an instance the min count will be ZERO if no object is created and the max count will be ‘n’ if n objects are crated.

Note – we invoke or refer to a static member we used the class name, whereas in case of instance member we used object of the class.
  • We use instance variable when data should be representing for a particular entity or object, whereas we use static variable when the data should be accessible to all entities or objects

No comments: