Showing posts with label Object Oriented Programming. Show all posts
Showing posts with label Object Oriented Programming. Show all posts

Friday, April 23, 2010

Overriding – ToString () – A Simplest approach to understand it

In C# Overriding can be achieved by use of the "override" keyword. To override a method means to replace it with a new way of handling data; I mean replacing the default behavior or extending it.

Here's an example of what I mean:
public class SimpleCar
 {
      int vwidth, vheight; //Private Data Member
      public int cWidth {  set { vwidth = value; } get { return vwidth; } }
      public int cHeight { set { vheight = value; } get { return vheight; } }
      public int cArea {  get { return (vwidth * vheight); }}
     //Not Overrided built-in ToString() method
 }
Moving forward with overriding,We will take help of “ToString()” method.As we know ToString is a built-in method that returns the name of the type of the object(in case of custom type).

Have a look at the Main() method which is used to call SimpleCar-
   namespace ConsoleApplication1 {
      class Program {
            static void Main(string[] args) {
                    SimpleCar mySimpleCar1 = new SimpleCar();
                    mySimpleCar1.cWidth = 13;
                    mySimpleCar1.cHeight = 15;

                   Console.WriteLine("The area occupied by {0}, width={1} and height={2} is: 
                   {3}.", mySimpleCar1, mySimpleCar1.cWidth, mySimpleCar1.cHeight,  mySimpleCar1.cArea);

                   Console.ReadLine(); }
       }
   }

Exact output will be:
The area occupied by ConsoleApplication1.SimpleCar, width=13 and height=15 is: 195.

*Here ‘ConsoleApplication1.SimpleCar’ name comes through the help of ToString() method, As I explained earlier. Now we will simply override built-in ToString() method in our code and then we’ll see what we get.

public class SimpleCar {
       int vwidth, vheight; //Private Data Member
       public int cWidth { set { vwidth = value; } get { return vwidth; } }
       public int cHeight { set { vheight = value; } get { return vheight; } }
       public int cArea { get { return (vwidth * vheight); } }

       //Overrided built-in ToString() method
       //Here I have provided an alias for the class(-type-)
       public override string ToString()  { return "Overrided SimpleCar"; }
}

The only change between this method and any other method is the use of the ‘override’ keyword. It is as simple as earlier. Now when the same Main() method is executed, the output will be:

The area occupied by Overrided SimpleCar, width=13 and height=15 is: 195.

I hope you get the reason, How ‘Overrided SimpleCar’ came into the picture.By overriding – I mean we have replaced the default behavior of built-in ToString () method.
-As of now we get bit understanding of overriding; now we need to delve into overloading and overriding together.
-
*Hasbro Power Tour Electric Guitar (Black)

Thursday, April 22, 2010

Abstraction vs Encapsulation


Abstraction is the process of taking a concept, identifying the attributes and behaviour and being able to turn that concept into code(Class) such that you will get an abstract view of the concept while Encapsulation is the process of organizing the required data types, methods to access them and defines a way to communicate through outer world, which mean's to get the job done.

In Object oriented programming abstraction is extremely important as by working more abstractly we can solve more and more difficult problems because we don’t have to concentrate on the lower level details.
  • “In another term we can say Abstraction comes first, Encapsulation satisfies what abstraction promise to do so.”
-Abstraction ask's to concentrate on “What” system does and encapsulation states “How” system does.


Elaborating topic more, For Abstraction we can say if we are not willing to know the cumbersome detailed information (because it might be too complex...) and willing to consider only meaningful data! Which help’s to "simplify" complex task and get clear arrangement/management.

While encapsulation shakes hands with if we didn’t want to let others access some important data and hence we put them within class and declare using access specifier. As a result, only the member functions can access them.

-Here I left one topic untouched i.e. information hiding, I will try to relate information hiding with this topic in next post.
-
*ASUS UL30A-X5 Thin and Light 13.3-Inch Black Laptop (12 Hours of Battery Life)

Sunday, January 4, 2009

Difference between virtual and abstract - Similar working nature but having different reason to be there

Well, Virtual methods allow subclasses to provide their own implementation of that method using the override keyword if they are wished while Abstract methods in a class contain no method body, and are implicitly virtual.Neither abstract or virtual can be declared private, since it will crush the purpose, and subclasses must override them using the same method signature.If a class has any abstact methods, then it must report itself as abstract I mean it has to, so that no instances of it can be created.
If a subclass needs to override a member (i.e. you can't specify a meaningful body in the base class, as it can't be defined), then it should be declared abstract and it will act as base-class. But if you just want to give the subclass the ability to override a method then it should be virtual.Any abstract member forces the entire class to be abstract, it means you can't create actual instances of the base class.
You must override when you deriving from abstract class. You can override methods (if for some reason you need to do something else) when you deriving from virtual.
In some cases you cannot provide an implementation for some methods, but method has to be there because it is part of the class interface. You want the programmers using the class to provide this implementation and you don't want to let them instantiate objects of this class because without this method it won't simply work. In this case you declare the method and the class as abstract. Abstract classes cannot be instantiated because they are not complete.
In other cases you can provide a default implementation of a method which is fair enough to make the control work even if not re-defined or changed, but you want to give the programmers using your class as a base class to provide their better implementation. In this case you declare the method as virtual thus, giving the programmers options whether to use the default or provide their own implementation and twist the results.
-
*Sharp Electronics PW-E550 Electronic Dictionary

Saturday, January 3, 2009

Exploring Static Classes and Static Class Members

To start with this topic I will say static class is mostly same as a non-static class, but having one major difference that a static class cannot be instantiated. In other words, I will say you cannot use the new keyword to create a variable of the static class type. Because there is no instance variable which needs to be initialized, you simply access the members of a static class by using the class name itself.

Since the type information for a static class is loaded by the .NET Framework CLR when the program that references the class is loaded. The program cannot specify exactly or will not guaranteed when the class is loaded. However, it is guaranteed that it will be loaded and to have its fields initialized and its static constructor will be called before the class is referenced for the first time in your program. A static constructor is only called or invoked one time, and a static class remains in memory througout or for the lifetime of the application domain in which executed program resides.


Let's in a few words draw the basic features of a static class:
*It contains only static members.
*It cannot be instantiated. (Object can not be created)
*It is also sealed. (Can not be inherited)
*It cannot contain instance constructors.(So that members will not be initialized)

Creating a static class is basically the same as creating a class that contains only static members and a private constructor, As a private constructor prevents the class from being instantiated. The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added and it will guarantee that instances of this class cannot be created.

Static classes are sealed i.e they cannot be inherited. They cannot inherit from any class except Object. Static classes can contain a static constructor. Non-static classes should also define a static constructor if the class contains static members that require non-trivial initialization.

A non-static class can contain static methods, fields, properties, or events. The static member is callable on a class even when no instance of the class has been created. The static member is always accessed by the class name, not the instance name. Only one copy of a static member exists, regardless of how many instances of the class are created. Static methods and properties cannot access non-static fields and events in their containing type, and they cannot access an instance variable of any object unless it is explicitly passed in a method parameter.


It is more emblematic to declare a non-static class with some static members, than to declare an entire class as static. Basically there are two common uses of static fields are to keep a count of the number of objects that have been instantiated, or to store a value that must be shared among all instances.

Static methods can be overloaded but not overridden, As they belong to the class, and not to any instance of the class. Although a field cannot be declared as static const, a const field is essentially static in its behavior. It belongs to the type, not to instances of the type. Therefore, const fields can be accessed by using the same ClassName.MemberName notation that is used for static fields. No object or instance is required.

As C# does not support static local variables (variables that are declared in method scope or have local scope). So it will be fair to declare static class members by using the static keyword before the return type of the member, as shown in the following example:


public class Bike{
public static int NoOfTyres = 2;
public static int SizeofFuelTank
{
get
{
return 13;
}
}
public static void Run() { }
public static event EventType RunOutOfFuel;
//Declare other non-static members..
}