Wednesday, February 10, 2010

Inheritance, Abstract Classes, Polymorphism

What is a class?
A class is a blue print or template of real world objects.
E.g. Consider a class Vehicle, which defines properties and behaviour of a vehicle like Vehicle Type, Name, Color, Accelerate, etc. where Vehicle Type, Name and Color are properties and Accelerate is a behaviour or functionality.
What is an object?
An object is an instance of a class. It represents real world entity. E.g. My Bajaj Pulsar is an object of type Vehicle which is a class.
What is inheritance?
It is an OOPS concept in which a class reuses properties and behaviour of some other class(base class). Along with that it also defines its own behaviour and properties.
What is an abstract class?
An abstract class is declared with keyword "abstract".
You cannot create an instance of an abstract class.
Abstract classes have atleast one abstract method or property. Abstract methods and properties don't have implementations.
e.g.
public abstract class Employee
{
//Abstract method
public abstract void AssignWork(string Name);
//Non abstract method
public string GetSalary(string Name)
{
//Logic for getting salary
return string.Empty;
}
}
Above class is an abstract class since it has an abstract method which is not having its implementation.
If you have an abstract method or property in your class and you don't declare that class as abstract, it would give compilation error.
An abstract class can also have non-abstract methods or properties. It is not necessary that all the methods and properties in abstract class are abstract.
Abstract classes are generally used when you have a requirement where you want to have some
functionality being implemented in similar way along with some other functionality to be implemented in different way.
e.g. consider above abstract class Employee and consider two types of class Developers and Testers which inherit from Employee.
Method of getting the salary of Developers and Testers would be same. So i have declared it non-abstract method. But the process of assigning work to both would be different. So i have declared AssignWork method as abstract. This method is not implemented in base class but will be implemented in Developers and Testers class.
To implement this abstract method, override keyword is used in child class. This is called Method Overriding.
e.g.

public class Developers : Employee
{
public override void AssignWork(string Name)
{
//Logic for assigning work to developers.
}
}
Now create an instance of Developers class and implement its methods.
public void Main()
{
Developers employee = new Developers();
string salary = employee.GetSalary("Haseet");
employee.AssignWork("Haseet");
}
As you can see, GetSalary method is shared between Developers and Testers class, while AssignWork is defined by both. This process of having two different behaviours but with same name is called Polymorphism.