Difference between Abstract class and interface-
1.
The abstract class allows concrete methods
(methods that have implementation) but interface doesn’t not.
2.
A class can inherit from only one class, but can
implement any number of interfaces.
3.
Interface doesn’t allow variables/constants to
be declared but abstract class allows for declaration of variables and
constants.
4.
You should consider using interface when you
design is complete in itself i.e. no further methods need to be added later on
the interface as any newly added method in interface need to be implemented in
all classes that implement that interface. On the other hand, if we need to add
a new method to an abstract class, we can provide default implementation of
that method in the abstract class and there is no need for existing
implementing classes to be changed in that case.
But, still a question needs to address “how we decide where
to implement interface and where we need to use interface”.
As word “interface” meaning itself describe contract between
2 classes where derived class need to implement all methods of interface. We
need to implement interface where there is no inheritance properties between
classes. We need declare interface when we need to force user to implement
certain methods. Let’s take an example.
public class Test : IDisposable
{
public Test()
{
//
// TODO: Add constructor logic
here
//
}
public void Dispose()
{
//throw new
Exception("The method or operation is not implemented.");
}
}
In above example, there is not generic similarity between
Test class and IDisposable interface. It is just a contract between 2 classes
and user has been forced to implement Dispose method.
On the other side, there is generic similarity between two
classes in case of abstract class. Let’s take an example.
abstract class Person
{
int
m_personID;
string
m_firstName;
string
m_lastName;
string
m_emailAddess;
const double minSalary = 3000;
public double returnSalary()
{
return
minSalary;
}
public int PersonID
{
get { return m_personID; }
set {
m_personID = value; }
}
public string FirstName
{
get { return m_firstName; }
set {
m_firstName = value; }
}
public string LastName
{
get { return m_firstName; }
set {
m_lastName = value; }
}
public string EmailAddess
{
get { return m_emailAddess; }
set {
m_emailAddess = value; }
}
}
public class Employee : Person
{
}
In the above example, we can see that there are properties
of base have been derived by child class. There is generic similarity between
Person and Employee class.