Sometimes I get often confused between when to derive class(use inheritance) and when not to.So for instance I have a code like this :
public class Payroll
{
public void ProcessPayroll(Employee e) //abstraction
{
e.ProcessPayroll();
}
}
Class Employee : Payroll
{
public virtual void ProcessPayroll()
{
//Process Payroll
}
}
class FulltimeEmployee : Employee
{
public override void ProcessPayroll()
{
//Payroll processing based on fulltime employee
}
}
This make sense :
class FulltimeEmployee : Employee
Becuase FulltimeEmployee is a Employee
so IS-A relationship
holds true here.
But I am confused here for below relationship so as to does this inheritance make sense as it is not an "IS-A" relationship
?
Class Employee : Payroll
Also Inheritance always have to follow IS-A relationship ?
Another Example :
Requirement says "Employee cannot exist without Company"
Based on this I did this :
public class Company
public class Employee : Company
Now does this make sense ?
Update :
I think above can be better represented using Aggregation
:
public class Company
{
Employee E; //because Company has-a Employee
}
But tomorrow if requirement says Company can exist without Employee too that means I have to come to this class and update the code.
Isnt this will violate Open and Closed principle
?