Let's look at the very important rule in OOPS for inheritance.
“Wherever object of parent class is expected, object of child class can go.”
Where This Can Be Used?
This rule is used to design loosely coupled systems so that we can optimize the code, thereby improving the system. Consider the following system:
Tightly Coupled System
The above system has a common function PrintCheque()
which is tightly coupled with specific type. PrintCheque()
does the same thing for all three classes but still it is defined in each class and takes specific type as parameter. This makes the system tightly coupled to the specific type.
Problem
Although the function does the same thing, it is defined in all three classes and takes parameter of specific type making it bound to that type. Also, in future, if we add another type, we have to redefine this function which will take object of that new type as parameter.
Solution
We declare a new class called Employee
and inherit these classes from employee
class.
Loosely Coupled System
The above designed system is loosely coupled. You can see that the PrintCheque()
function now takes parameter of type Employee
, so any class that inherits from Employee
can be passed as parameter. Also, any new type added, when inherited from Employee
class, will be able to call this function thus making our system a loosely coupled system.
Source Code
Employee
Class:
abstract class Employee
{
private string _name;
private double _salary;
public Employee(string mname, double mamt)
{
_name = mname;
_salary = mamt;
}
public string Name {
get
{
return _name;
}
}
public double Salary
{
get {
return _salary;
}
}
public abstract double NetSalary();
public static void PrintCheque(Employee temp)
{
Console.WriteLine("Name={0} Salary={1}", temp.Name, temp.NetSalary());
}
}
Manager
Class:
class Manager:Employee
{
private double _taxes = 0.25;
public Manager(string mname, double mamt)
: base(mname, mamt)
{ }
public override double NetSalary()
{
return Salary * (1 - _taxes);
}
public void PlanProjects()
{
Console.WriteLine("Manager plans projects");
}
}
Analyst
Class:
class Analyst:Employee
{
double _taxes = 0.20;
double _compoff = 0.10;
public Analyst(string mname, double mamt)
: base(mname, mamt)
{
}
public override double NetSalary()
{
return Salary * (1 - _taxes + _compoff);
}
public void DesignSystems()
{
Console.WriteLine("Analyst designs systems");
}
}
SalesMan
Class:
class SalesMan:Employee
{
double _comm = 0.05;
public SalesMan(string mname, double mamt) : base(mname, mamt) { }
public override double NetSalary()
{
return Salary * (1 + _comm);
}
public void Markets()
{
Console.WriteLine("Salesman sells");
}
}
Main
class Program
{
static void Main(string[] args)
{
Manager emp1 = new Manager("abc", 700000);
Analyst emp2 = new Analyst("pqr", 500000);
SalesMan emp3 = new SalesMan("lmn", 200000);
Employee.PrintCheque(emp1);
Employee.PrintCheque(emp2);
Employee.PrintCheque(emp3);
}
}