Wednesday, March 4, 2009

Ch 5 C #: Classes and Methods, Part 1

5. Classes and Methods – Part 1

Defining a class :
The keyword class is used to define a class. The basic structure of a class is as follows:

class identifier
{
Class-body
}
Where identifier is the name given to the class and class-body is the code that makes up the class.


Class declarations:
After a class is defined, we use it to create objects. A class is just a definition used to create objects. A class by itself cannot hold information. A class cannot perform any operations. A class is used to declare objects. The object can then be used to hold data and perform operations.

The declaration of an object is called instantiation. We say that an object is an instance of a class.

The format of declaring an object from a class is as follows:

class_name object_identifier = new class_name();

Here,
class_name is the name of the class,
object_identifier is the name of the object being declared.

Example 1:
We create an object called c1 of class Circle as follows:

Circle c1 = new Circle();
On the right side, the class name with parenthesis i.e., Circle(), is a signal to construct – create – an object of class type Circle.

Here:
• Name of the class is Circle.
• Name of the object declared is c1.
• The keyword new is used to create new items. This keyword indicates that a new instance is to be created. In this case, the new instance is the object called c1.

Members of a Class:
A class can hold two types of items:
• data members, and
• function members (methods).

Data Members or fields:
Data members include variables and constants. Data members can themselves be classes. Data members are also called as fields. Data members within a class are simply variables that are members of a class.

Example 1: Consider a class called Circle defined as follows:
class Circle
{
public int x, y; // co-ordinates of the centre of the circle
public int radius;
}

The keyword public is called the access modifier.

Example 2: Create a class called FullName that contains three strings that store the first, middle and last name of a person.
class FullName
{
string firstname;
string middlename;
string lastname;
}

Example 3: Create a class called Customer that contains account holder’s bank account no (long), balance amount (float), and a Boolean value called status (active/inactive account);
class Customer
{
long acno;
flaot balance;
boolean status;
}

How to access Data Members?
Consider a class called Circle. We declare two objects c1 and c2 of this class. Now both the objects can be represented as follows:







If we want to refer to the fields x and y then we must specify which object we are referring to. So we use the name of the object and the data member (field name) separated by the dot operator. The dot operator is also called the member of operator.

To refer to data x and y of object c1, we write: c1.x and c1.y
Similarly, to refer to data x and y of object c2, we write: c2.x and c2.y


Methods:
1. A method is a code designed to work with data. Think of a method like a function.
2. Methods are declared inside a class.
3. Methods are declared after declaring all the data members (fields).

Declaring Methods:
Methods are declared inside the body of a class. The general declaration of a method is :

modifier type methodname (formal parameter list)
{
method body
}

There are 5 parts in every method declaration:
1. Name of the method (methodname)
2. Type of value the method returns
3. List of parameters (formal parameters) (think of these as inputs for the method)
4. Method modifier, and
5. Body of the method.

Examples:
void display(); // no parameters
int cube (int x); // one int type parameter
float area (float len, int bre); // one float, one int parameter, return type float

How is a method invoked (or called)?
A method can be invoked or called only after it has been defined. The process of activating a method is known as invoking or calling.

A method can be invoked like this:
Objectname.methodname(actual parameter list);

Nesting of Methods:
A method of a class can be invoked only by an object of that class if it is invoked outside the class. But a method can be called using only its name by another method belonging to the same class.This is known as nesting of methods.

In the following program, the class Nesting defines two methods, Largest() and Max(). The method Largest() calls the method Max().

Program 1: To compute the largest of two integers.

using System;

namespace Method2
{
class Nesting
{
public void Largest(int m, int n)
{
int large = Max(m, n); // nesting
Console.WriteLine(large);
}

int Max(int a, int b)
{
int x = (a > b) ? a : b;
return (x);
}
}

class NestTesting
{
public static void Main()
{
Nesting next = new Nesting();
next.Largest(190, 1077);
Console.ReadLine();
}
}
}

Method Parameters:
When a method is called, it creates a copy of the formal parameters and local variables of that method. The argument list is used to assign values to the formal parameters. These formal parameters can then be used just like ordinary variables inside the body of the method.
When a method is called, we are interested in not only passing values to the method but also in getting back results from that method. It is just like a function which takes input via formal parameters and returns some calculated result.

To manage the process of passing values and getting back results from a method, C# supports four types of parameters:

1. Value parameters - to pass parameters into methods by value.
2. Reference parameters - to pass parameters into methods by reference.
3. Output parameters - to pass results back from a method.
4. Parameter arrays - used to receive variable number of arguments when called.

PASS BY VALUE:
i) The default way of passing method parameters is “pass by value”.
ii) A parameter declared with no modifier is passed by value and is called a value parameter.
iii) When a method is called (or invoked), the values of the actual parameters are assigned to the corresponding formal parameters.
iv) The method can then change the values of the value parameters.
v) But the value of the actual parameter that is passed to the method is not changed.
vi) Thus formal parameter values can change, but actual parameter values are not changed.
vii) This is because the method refers only to the copy of the parameter passed to it.
viii) Thus, pass by value means pass a copy of the parameter to the method.

The following example illustrates the concept of pass-by-value:

using System;

namespace PassbyValue
{
class Program
{
static void multiply(int x)
{
x = x * 3;
Console.WriteLine("Inside the method, x = {0}", x);
}

public static void Main()
{
int x = 100;

multiply(x);
Console.WriteLine("Outside the method, x = {0}", x);

Console.ReadLine();
}
}
}
In the above program, we have declared a variable x in method Main. This is assigned a value of 100. When the method multiply is invoked from Main(), the formal parameter is x in the method, while x in the calling part is called the actual parameter.

PASS BY REFERENCE:
i) The default way of passing values to a method is by “pass by value”.
ii) We can force the value parameters to be passed by reference. This is done by using the ref keyword.
iii) A parameter declared with the ref keyword is a reference parameter.
E.g., void Change (ref int x). In this case, x is declared as a reference parameter.
iv) A reference parameter does not create a new storage location. It represents or refers to the same storage location as the actual parameter.
v) Reference parameters are used when we want to change the values of the variables in the calling method.
vi) If the called method changes the value of the reference parameter, this change will be visible in the calling method also.
vii) A variable must be assigned a value before it can be passed as a reference variable.

The following example illustrates the use of reference parameters to exchange values of two variables.

using System;

namespace PassByRef
{
class Program
{
static void Swap(ref int x, ref int y)
{
int temp;

temp = x;
x = y;
y = temp;
}

static void Main(string[] args)
{
int m = 100;
int n = 200;

Console.WriteLine("Before swapping:");
Console.WriteLine("m = {0}, n = {1}", m, n);

Swap(ref m, ref n);

Console.WriteLine("After swapping:");
Console.WriteLine("m = {0}, n = {1}", m, n);

Console.ReadLine();

}
}
}
OUTPUT PARAMETERS:
i) Output parameters are used to pass values back to the calling method.
ii) Such parameters are declared with the out keyword.
iii) An output parameter does not create a new storage location.
iv) When a formal parameter is declared with the out keyword, the corresponding actual parameter must also be declared with the out keyword.
v) The actual output parameter is not assigned any value in the function call.
vi) But every formal parameter declared as an output parameter must be assigned a value before it is returned to the calling method.

The following program illustrates the use of out parameter:

using System;

namespace OutParameters
{
class Program
{
static void square (int x, out int n)
{
n = x * x;
}

public static void Main()
{
int n; // no need to initialize this variable
int m = 5;

square(m, out n);

Console.WriteLine("n = {0}", n);
Console.ReadLine();
}
}
}


SOLVED EXAMPLES:

1. Write a PrintLine method that will display a line of 20 character length using the * character.

using System;

namespace StarPrg
{
class CStar
{
public void PrintLine(int n)
{
for(int i = 1; i <= n; i++)
{
Console.Write("*");
}
Console.WriteLine();
}
}

class MStar
{
static void Main()
{
CStar p = new CStar();

p.PrintLine(20);

Console.ReadLine();
}
}
}

2. Modify the PrintLine method such that it can take the “character” to be used and the “length” of the line as the input parameters. Write a program using the PrintLine method.

using System;

namespace StarPrg
{
class CStar
{
public void Star(int n, char ch)
{
for (int i = 1; i <= n; i++)
{
Console.Write(ch);
}
Console.WriteLine();
}
}

class MStar
{
static void Main()
{
CStar p = new CStar();

Console.WriteLine("How many characters ?");
int num = int.Parse(Console.ReadLine());

Console.WriteLine("Which character ? ");
char ch = char.Parse(Console.ReadLine());

p.Star(num, ch);

Console.ReadLine();
}
}
}

No comments:

Post a Comment