Programming in almost language

Thi s is the site where you may share your knowledge and experience to eachother..

Archive for the ‘Object Oriented Programming’ Category

A Twisted Look at Object Oriented Programming

A Twisted Look at Object Oriented Programming in C# – Classes, Objects, and Properties

Posted by Praveen Kumar on March 20, 2008

Classes, Objects, and Properties

Why program with objects and inheritance?

Simply put, programming with objects simplifies the task of creating and maintaining complex applications. OOP is a completely different way of thinking that differs significantly from the more traditional function driven sequential programming model of old. Programming with objects without inheritance is “object-based” programming. Adding inheritance to objects is “object-oriented” programming. OOP provides built in support for code reuse (inheritance) and support for runtime variations in program behavior (polymorphism). Without attempting to define these terms, OOP at a minimum:

  1. Simplifies the creation and maintenance of complex applications.
  2. Promotes code reuse.
  3. Allows flexibility in runtime program behavior (a very cool feature).

What is OOP?

Well, lets cut right to the point. What the heck is Object Oriented Programming? Answer: It is a whole new way of thinking about programming! It is a way of modeling software that maps your code to the real world. Instead of creating programs with global data and modular functions, you create programs with “classes”. A class is a software construct that maps to real world things and ideas. Think of a class as a blueprint that contains information to construct a software object in memory. Unlike a simple data structure, software objects contain code for both data and methods. The class binds the data and methods together into a single namespace so that the data and methods are intertwined.

Just as you can build more than one house from a single blueprint, you can construct multiple software objects from a single class. Each object (represented by code in memory) is generated from a class and is considered an “instance” of the class. Since each instance of the class exist in separate memory space, each instance of the class can have its own data values (state). Just as multiple houses built from a single blueprint can differ in properties (e.g. color) and have identity (a street address), multiple objects built from a single class can differ in data values and have a unique identifier (a C++ pointer or a reference handle in C#). Got that! Now take and break and re-read this paragraph. When you come back, you can look at some C# code.

What is a class?

A class is a software construct, a blueprint that can describe both values and behavior. It contains the information needed to create working code in memory. When you create an object, you use the information in the class to generate working code. Let’s create a simple program that models a toaster! The toaster is a real life object. The toaster can have state such as secondsToToast and has a behavior, MakeToast(). Here is our first toaster class in C#:

class Toaster1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: Add code to start application here
//
Toaster1 t= new Toaster1();
System.Console.WriteLine(t.MakeToast());
System.Console.ReadLine();
}
private int secondsToToast= 10;
public string MakeToast()
{
return "Toasted for "+secondsToToast.ToString()+" seconds.";
}
}

If you execute this program, the output is:

“Toasted for 10 seconds.”

A working toaster yes, but not very useful unless you like 10-second toast <g>.

What is an object?

An object is an instance of a class. A specific class describes how to create a specific object in memory. So the class must contain information about the values and behaviors that each object will implement. You can create an object using the reserved word “new”. In our Toaster1 application, you create a single instance of the Toaster1 class with the call:

Toaster1 t= new Toaster1();

The reference variable “t”, now contains a reference to a unique instance of the Toaster1 class. You use this reference variable to “touch” the object. In fact, if you set the reference variable “t” to null, so that the object is no longer “touchable”, the garbage collector will eventually delete the Toaster1 object!

t= null;
// If "t" contains the only reference to the Toaster1 object, the object can be garbage collected. (Strictly speaking, if the Toaster1 object cannot be "reached", it can be garbage collected.)

MakeToast() is a public method of the Toaster1 object so it can be called from outside the class (Main) using the reference variable “t” to touch the object’s behavior:

t.MakeToast();

Since each object exists in a separate memory space, each object can have state, behavior and identity. Our Toaster1 object has identity since it is unique from any other object created from the Toaster1 class:

Toaster1 t2= new Toaster1();

Now there are two instances of the Toaster1 class. There are two reference variables “t” and “t2”. Each reference variable identifies a unique object that exists in a separate memory address. Since each object contains a method MakeToast(), each object has behavior. Finally, each object contains a value “secondsToToast()”. In a sense, each object now has its own “state”. However, the state is the same for each object! This is not a very useful class design. In fact, the Toaster1 class is not a good representation of a real world toaster since the toast time is immutable.

Here is a second run at the Toaster class that demonstrates the use of public “accessors”, get and set methods. This is a standard idiom in OOP. The actual data is declared private (or protected) so that users of the class cannot access the underlying data. Instead, public methods are exposed to the callers of the class to set and get the underlying hidden data values.

Note: The modifiers “private”, “protected” and “public” are access modifiers that control the visibility of methods and data. The compiler will enforce these visibility rules and complain if you say try to touch a private variable from outside the class. “Public” methods and data are visible to any caller. “Private” methods and data are only visible and “touchable” within the class. “Protected” is a special level of access control of great interest to object oriented programmers, but is a subject that must be deferred to the chapter on inheritance. If you don’t declare an access modifier, the method or variable is considered private by default.

using System;
namespace JAL
{
/// <summary>
/// Summary description for class.
/// </summary>
///
class Toaster2
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Toaster2 t= new Toaster2();
t.SetSecondsToToast(12);
Console.WriteLine(t.MakeToast());
Console.ReadLine();
}
private int secondsToToast= 0;
public string MakeToast()
{
return "Toasted for "+GetSecondsToToast().ToString()+" seconds.";
}
// Public Accessor Functions, Get and Set
public bool SetSecondsToToast(int seconds)
{
if (seconds > 0)
{
secondsToToast= seconds;
return true;
}
else
{
secondsToToast= 0;
return false;
}
}
public int GetSecondsToToast()
{
return secondsToToast;
}
}
}

The callers of the class cannot “touch” the secondsToToast variable which remains private or “hidden” from the caller. This idiom is often called “encapsulation” so that the class encapsulates or hides the underlying data representation. This is an important aspect of OOP that allows the writer of the class to change the underlying data representation from say several variables of type int to an array of ints without affecting the caller. The class is a “black box” that hides the underlying data representation. In this new version of toaster, Toaster2, there are two new methods: SetSecondsToToast() and GetSecondsToToast(). If you look at the “setter” method it validates the callers input and sets the value to zero if the callers input is invalid (<0):

public void SetSecondsToToast(int seconds)
{
if (seconds > 0)
{
secondsToToast= seconds;
}
else
{
secondsToToast= 0;
}
}

The “getter” method really does not do much simply returning the private data value “secondsToToast”:

public int GetSecondsToToast()
{
return secondsToToast;
}

What is a property?

C#.NET implements a language idiom called a “property”. In a nutshell, “a property is a method that appears as a variable”. By convention, a property name starts with an uppercase letter. Here is our new version of Toaster that replaces the get and set methods with properties:

using System;
namespace JAL
{
/// <summary>
/// Summary description for class.
/// </summary>
///
class Toaster3
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Toaster3 t= new Toaster3();
t.SecondsToToast= 12; // the property idiom
Console.WriteLine(t.MakeToast());
Console.ReadLine();
}
private int secondsToToast= 0;
public string MakeToast()
{
return "Toasted for "+secondsToToast.ToString()+" seconds.";
}
// Properties
public int SecondsToToast
{
get {return secondsToToast;}
set
{
if (value > 0)
{
secondsToToast= value;
}
else
{
secondsToToast= 0;
}
}
}
}
}

Here are the new setter and getter methods as properties:

// Properties
public int SecondsToToast
{
get {return secondsToToast;}
set {
if (value > 0) {
secondsToToast= value;
} else {
secondsToToast= 0;
}
}
}

The reserved word “value” is used to represent the caller’s input. Note the syntax used to call a property. To set a property use:

t.SecondsToToast= 12;

The method set() now appears as a variable “SecondsToToast”. So “a property is a method that appears as a variable”.

Well, congratulations. You have constructed your first real world class in C#. Since this is a hands on tutorial, I strongly urge you to compile the Toaster3 code and experiment.

Posted in Object Oriented Programming | Leave a Comment »

Generic Class

Posted by Praveen Kumar on March 20, 2008

This articles that shows how to declare and use generic methods in the C# programming language. In this article, i introduce the concept of generics.I will explain you an example using overloaded methods to motivate the need for generic methods. we reimplement the overloaded methods from the example using a single generic method.

Generic classes enable you to specify, with a single class declaration, a set of related classes.

Generic methods enable you to specify, with a single method declaration, a set of related methods.

Similarly, generic interfaces enable you to specify, with a single interface declaration, a set of related interfaces.

Generics provide compile-time type safety. [Note: You can also implement generic structs and delegates.]

We can write a generic method for sorting an array of objects, then invoke the generic method separately with an int array, a double array, a string array and so on, to sort each different type of array.

The compiler performs type checking to ensure that the array passed to the sorting method contains only elements of the same type.

We can write a single generic Stack class that manipulates a stack of objects, then instantiate Stackints, a stack of doubles, a stack of strings and so on. The compiler performs type checking to ensure that the Stack stores only elements of the same type.

I will explain examples of generic methods and generic classes.

How to declare and use Generics Method

I present an example using overloaded methods to motivate the need for generic methods.

I reimplement the overloaded methods from the example in this article using a single generic method.

Overloaded methods are often used to perform similar operations on different types of data. The below example contains three overloaded DisplayArray method(color in red).

These methods display the elements of an int array, a double array and a char array, respectively. Soon, we will reimplement this program more concisely and elegantly using a single generic method.

using System;
class OverloadedMethods
{
static void Main( string[] args )
{
// create arrays of int, double and char
int[] intArray = { 1, 2, 3, 4, 5, 6 };
double[] doubleArray = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 };
char[] charArray = { ‘H’, ‘E’, ‘L’, ‘L’, ‘O’ };

Console.WriteLine( “Array intArray contains:” );
DisplayArray( intArray ); // pass an int array argument
Console.WriteLine( “Array doubleArray contains:” );
DisplayArray( doubleArray ); // pass a double array argument
Console.WriteLine( “Array charArray contains:” );
DisplayArray( charArray ); // pass a char array argument
} // end Main
// output int array

static void DisplayArray( int[] inputArray )
{
foreach ( int element in inputArray )
Console.Write( element + ” ” );
Console.WriteLine( “\n” );
} // end method DisplayArray
// output double array

static void DisplayArray( double[] inputArray )
{
foreach ( double element in inputArray )
Console.Write( element + ” ” );
Console.WriteLine( “\n” );
} // end method DisplayArray
// output char array

static void DisplayArray( char[] inputArray )
{
foreach ( char element in inputArray )
Console.Write( element + ” ” );
Console.WriteLine( “\n” );
} // end method DisplayArray
} // end class OverloadedMethods

OUTPUT

Array intArray contains:
1 2 3 4 5 6

Array doubleArray contains:
1.1 2.2 3.3 4.4 5.5 6.6 7.7 

Array charArray contains:
H E L L O

Generic Method Implementation

If the operations performed by several overloaded methods are identical for each argument type, the overloaded methods can be more compactly and conveniently coded using a generic method.

You can write a single generic method declaration that can be called at different times with arguments of different types. Based on the types of the arguments passed to the generic method, the compiler handles each method call appropriately.

All generic method declarations have a type parameter list delimited by angle brackets (< E > in this example) that follows the method’s name.

using System;
using System.Collections.Generic;

class GenericMethod
{
static void Main( string[] args )
{
// create arrays of int, double and char
int[] intArray = { 1, 2, 3, 4, 5, 6 };
double[] doubleArray = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 };
char[] charArray = { ‘H’, ‘E’, ‘L’, ‘L’, ‘O’ };

Console.WriteLine( “Array intArray contains:” );
DisplayArray( intArray ); // pass an int array argument
Console.WriteLine( “Array doubleArray contains:” );
DisplayArray( doubleArray ); // pass a double array argument
Console.WriteLine( “Array charArray contains:” );
DisplayArray( charArray ); // pass a char array argument
} // end Main

// output array of all types
static void DisplayArray< E >( E[] inputArray )
{
foreach ( E element in inputArray )
Console.Write( element + ” ” );
Console.WriteLine( “\n” );
} // end method PrintArray
} // end class GenericMethod

Array intArray contains:
1 2 3 4 5 6

Array doubleArray contains:
1.1 2.2 3.3 4.4 5.5 6.6 7.7 

Array charArray contains:
H E L L O

Each type parameter list contains one or more type parameters, separated by commas.

A type parameter is an identifier that is used in place of actual type names. The type parameters can be used to declare the return type, the parameter types and the local variable types in a generic method declaration;

The type parameters act as placeholders for the types of the arguments passed to the generic method.

A generic method’s body is declared like that of any other method.

Note that the type parameter names throughout the method declaration must match those declared in the type parameter list.

For example, element in the foreach statement as type E, which matches the type parameter (E) declared.

Also, a type parameter can be declared only once in the type parameter list but can appear more than once in the method’s parameter list.

Type parameter names need not be unique among different generic methods.

Common Programming Error:

  • If you forget to include the type parameter list when declaring a generic method, the compiler will not recognize the type parameter names when they are encountered in the method. This results in compilation errors.
  • It is recommended that type parameters be specified as individual capital letters. Typically, a type parameter that represents the type of an element in an array (or other collection) is named E for “element” or T for “type.”

Posted in Object Oriented Programming | Leave a Comment »