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

Constructor


When an object memory is being utilized by multiple objects and references in such case if NULL is assign to any of them still that memory can be utilized by others who are pointing the memory.
To test this rewrites the code under main method of class first as following.
{
First f1 = new First();
First f2 = f1;
f1 = null;
Console.WriteLine(f2.x);
Console.WriteLine(f1.x); //invalid
Console.ReadLine();

}
whenever the object of a class is created internally following thing tack place.
  1. Reads the classes - in this process it identify each and every member i.e. defined in the class.
  2. Invokes the Constructors of classes.
  3. Allocate the required memory for execution.
Constructor It is a special method i.e. present in every class responsible for initializing the variable of class.
A constructor method will always have the same name of your class and it is non value returning.
Every class must and should required constructor in it, if it all, it has to execute. so a programmer must define a constructor in the class if not defined , on behalf of the programmer compiler tack the responsibility of defining constructor in the class while compilation .
If a class is defined as following:
Class Test
{
int x; string s; bool b;
}
After compilation it will be looking like as –
class Test
{
x = 0; s = null; b = false;
}
Note – Implicitly defined constructor will always be public.
We can also define a constructor explicitly as following –
[<modifier>]<NAME>([<param def’s>])
{
- stmts
}
Add a class ConDemo.cs and write the following :-
using System;
Namespace oopsProject
{
class ConDemo
{
ConDemo()
{
Console.WriteLine("constructor");
}
void Demo()
{
Console.WriteLine("method");
}
static void Main()
{
ConDemo cd1 = new ConDemo();
ConDemo cd2 = new ConDemo();
ConDemo cd3 = cd2;
cd1.Demo(); cd2.Demo();
cd3.Demo();
Console.ReadLine();
}
}
}


While creating the object of class we explicitly call the constructor of the class to execute .
ConDemo.cd1 = new ConDemo(); in this we are making the constructor.
- Each time we call the constructor of the class that many no. of times memory allocation is also takes 3place.
Constructors is two types 
  1. zero Argument / default constructor
  2. Parameterized constructor
If a constructor doesn’t have any parameters to it. It is default or zero argument constructors. These constructor can be defined either by a programmer or will be defined by compiler implicitly, provided the class doesn’t contain any constructor in it.
If a constructor has any parameter it is referred as parameterized constructor and these can be defined only by programmer explicitly
If a constructor is parameterized we need to send values to the parameters while creating object of class. To test this rewrites the constructor in our program ConDemo as following.
ConDemo(int x)
{
Console.WriteLine("constructor :" + x);
}
Now while creating the object under main we need to send values to the constructor as following
ConDemo cd1 = new ConDemo(10);
ConDemo cd2 = new ConDemo(20);
- Add the class Maths.cs and write the following .
using System;
namespace oopsProject
{
class Maths
{
int x, y;
Maths(int a, int b)
{
x = a;
y = b;
}
void Add()
{
Console.WriteLine(x + y);
}
void Sub()
{
Console.WriteLine(x - y);
}
void Mul()
{
Console.WriteLine(x * y);
}
void Div()
{
Console.WriteLine(x/y);
}
static void Main()
{
Maths obj = new Maths (100,50);
obj.Add(); obj.Sub();
obj.Mul(); obj.Div();
Console.ReadLine();
}
}
}
Whenever a class required any initialization values for its variable to execute we need to pass value to the variables using constructor of the class. In our above program the class required values to the variable x and y for execution of the four methods on the class. So using constructor we have send values to the variables, so that the method are getting executed.

Create the OBJECT of a class


As per encapsulation method has to be defined inside a class and to invoke them we need to create object of that class.
We create the OBJECT of a class as following –
<class><obj.> = new <class> ([<list of values > ])
Program p = new Program ();
Or
Program p;
p = new Program();
Object of a class can be created anywhere within the class it can also be created in other classes also, but while creating in a class we create under main method because it is the main entry point of your program.
Open visual Studio  click new Project  select Console application Template  name it as oops project and click ok . Now write following code under the default class program.

using System;
namespace oopsProject
{
class Program
{
//No input and no return value
void test1()
{
Console.WriteLine("First Method ");
}
// No Return value but has input
void test2(int x, int max)
{
for (int i = 1; i <= max; i++)
Console.WriteLine("{0}* {1} = {2}", x, i, x * i);
}
// NO input but has a return value
string test3()
{
return "Third method";
}
// has input and return value
string test4(string name)
{
return "hello" + name;
}
// named and optional parameter (C# 4.0)
void Addnums(int x, int y = 50, int z = 25)
{
Console.WriteLine(x + y + z);
}
// Returns Multiple values as output
void Math1(int x, int y, ref int a, ref int b)
{
a = x + y;
b = x * y;
}
void Math2(int x, int y, out int a, out int b)
{
a = x - y;
b = x / y;
}
static void Main(string[] args)
{
Program p = new Program();
p.test1();
p.test2(5, 5);
Console.WriteLine(p.test3());
Console.WriteLine(p.test4("Prabodh"));
// Invoking method with default value can
//be done in any of the following way :
p.Addnums(100);
p.Addnums(100, 100);
p.Addnums(100, z: 100);
p.Addnums(100, 100, 100);
// Invoking method with input & output params :
int m = 0, n = 0; //initializing is mandatory
p.Math1(100, 50, ref m, ref n);
Console.WriteLine(m + " " + n);
int q, r; //Initialization is optional
p.Math2(100,50, out q, out r);
Console.WriteLine(q + " " + r);
Console.ReadLine();
}
}
}
- In C# 4.0 we are given with the feature named and optional parameters, which allows passing default values to any parameter of your method. The advantage in this case is while invoking the method it will only be optional to pass values to those parameters.

The execution of a method with output parameters tacks place as following –
A variable i.e. declared using ref or out keyword is a pointer variable, which doesn’t contain any values in it , what it contains is address of another variable but any manipulation we perform onref or out variables will be affected to the variable whose address they contain in them.

Note – A variable declared as ‘ref’ required initialization while invoking the method where as in case of ‘out’ it is optional.
Add a class.cs under the project and write the following code
class First
{
int x=100;
static void Main ()
{
First F; //F is variable
F = new First(); // f is an object
Console.WriteLine(F.x);
Console.ReadLine();
}
}
- A variable or a method which is declared in a class is referred as member of the class where to invoke a member we must create the Object of the class (NOT required for static members)
- The object of a class can be created only with the use of new operator. If new is not used there will not be any memory allocation for the object and more over it is only consider as variable of the class.
We can destroy the object which got created at any particular point of time by assigning NULL to it so that object gets marked as unused and cannot be used any more to invoke the members.

- To test this rewrite the following code under you privies class first main method.
First F = new First();
Console.WriteLine(F.x);
F = null; //destroying the object
Console.WriteLine(F.x); //Invalid
Console.ReadLine();
- We can create any number of objects to a class where each object will create will allocate the memory separately for each members and manipulations performed on members of one object will not be reflected to members of other object
- To test this rewrites the code under main method of class first as following.
First F1 = new First();
First F2 = new First();
Console.WriteLine(F1.x + “ ” +F2.x );
F1.x = 500;
Console.WriteLine(F1.x + “ ” +F2.x );
Console.ReadLine();
- We can assign object of a class to the variable of some class. So that the variable will be consuming the memory of the object which was assign to it. Once the assignment is performed the variable is now referred as a reference.
- Because the object and reference are consuming the same memory manipulation performed on the members through object reflect to reference and Vis...
- To test this rewrites the code under main method of class first as following.
First F1 = new First();
First F2 = F1;
Console.WriteLine(F1.x + “ ” +F2.x );
F1.x = 500;
Console.WriteLine(F1.x + “ ” +F2.x );
Console.ReadLine();

Defining Method under classes



[< modifiers >]void|type <name>([<param defn’s>])
{
-stmts
}
  • method referred as a sub-program is a block of code that can be reused. We can categorize them into value returning and Non value returning methods.
  • Modifiers - or some special keywords which can be used on a method like Public, Private, Virtual, Abstract etc.
  • Void | type - we used void to a method to specify it was non- value returning where as if the method is value returning using the type we need to tell the type of value it was returning .

Note - Type need not be only predefined data types like int, float, bool etc. that can also be class type also.
  • Using the optional parameter “param defn’s” we can pass parameters to a method as following.

[ref |out] <type> < var> [ = value] [,…n]
.----------------------------
A method can be defined with any number of parameters, where these parameters are divided into two types.
  1. input parameters
  2. Output Parameters.
  • Input parameters are used for tacking a value into the method for execution, whereas output parameters are used for returning the value out of the method after execution.
  • To tack input parameter we used pass by value” mechanism and for output parameter we used “pass by reference” mechanism, which is similar to pass by address in “C” language.
Note – both “pass by address and pass by reference “uses the concept of pointer but “pass by address is explicit pointer” where address are managed by programmer, whereas “pass by reference is implicit pointer” where address are managed by garbage collector implicitly.
  • To pass a parameter using pass by reference mechanism it should be prefixed with either “ref | out “keywords.
  •  [ = value ] - In C# 4.0 we are giving with a feature named and optional parameter, which allows defining a parameter with a default value while calling the method passing values to that parameter becomes optional.