Hi,
Of course Abstraction is interested with Inheritance. But there are some important points.
First of all when you mark a class as abstract you cannot create an instance. This is very important. Abstract classes are used to be inherited only.
But when you inherited from a non abstract class you can create instance from both of derived and base classes.
So we can say abstract classes are used to generate new types,to be inherited not to create instance !
And of course abstraction is interested with Polymorphism. Abstraction forces us to Polymorphism.
For example you have a base Employee class like below:
public class Employee
{
public string Name { get; set; }
public double Salary { get; set; }
public void IncreaseSalary(double rate)
{
this.Salary += (this.Salary * rate / 100);
}
}
Now when we create SalesRepresentative class like below we should inherit it from Employee because SalesRepresentative is an Employee.
public class SalesRepresentative : Employee
{
public double AnnualSalesAmount { get; set; }
}
Now SalesRepresentative object has IncreaseSalary method because it is inherited from Employee. But in generally Sales Representatives' and Employee's Salaries are increased by different ways for example according to their AnnualSalesAmount.
In this case you should be able to change method code of IncreaseSalary from SalesRepresentative but you can't. Actually now you are across with Polymorphism
Now Let's come to abstraction. If you want to change the default code of IncreaseSalary from inherited class there are 2 choices. First marking the method as Virtual. And the second one is marking it as abstract.
The difference is If you mark it as virtual. You don't have to implement it in SalesRepresentative but If you mark it as abstract you have to implement it and you should'nt forget an abstract member can only be in abstract classes. Examine the example below
public abstract class Employee
{
public string Name { get; set; }
public double Salary { get; set; }
public abstract void IncreaseSalary(double rate);
}
public class SalesRepresentative : Employee
{
public double AnnualSalesAmount { get; set; }
public override void IncreaseSalary(double rate)
{
if (this.AnnualSalesAmount > 100000)
{
this.Salary += (this.Salary * (rate + 5) / 100);
}
else
{
this.Salary += (this.Salary * rate / 100);
}
}
}