We use interface and
abstract class for the base class in our application.
We cannot make
instance of Abstract Class as well as Interface.
Here are few
differences in Abstract class and Interface as per the definition.
Abstract class can
contain abstract methods, abstract property as well as other members (just like
normal class).
Interface can only
contain abstract methods, properties but we don’t need to put abstract and
public keyword. All the methods and properties defined in Interface are by
default public and abstract.
Now a billion dollar
question;
How can we take
decision about when we have to use Abstract Class and when Interface.
Basically, abstract
class is an abstract view of any real world entity and an interface is more
abstract one. When we thinking about the entity there are two things one is
intention and one is implementation. Intention means I know about the entity
and also may have idea about its state as well as behavior but don’t know about
how its looks or works or may know partially. Implementation means actual state
and behavior of entity.
When we create an interface,
we are basically creating a set of methods without any implementation that must
be overridden by the implemented classes. The advantage is that it provides a
way for a class to be a part of two classes: one from inheritance hierarchy and
one from the interface.
When we create an
abstract class, we are creating a base class that might have one or more
completed methods but at least one or more methods are left uncompleted and
declared abstract. If all the methods of an abstract class are uncompleted then
it is same as an interface. The purpose of an abstract class is to provide a
base class definition for how a set of derived classes will work and then allow
the programmers to fill the implementation in the derived classes.
Following are some
points whether to implement Abstract Class or Interface.
Abstract Class versus
Interface
1. When the properties
and methods (behaviors) that are shared with commonly in most classes and you
are using these members frequently in your application then making the Abstract
Class is a best practice.
2. When the properties
and methods are least likely used in your application and the implementation is
very from class to class then use the interface for this purpose.
3. When derived
classes having some commonly implemented behaviors, make these methods with
default functionality in abstract classes and use in all child classes.
4. Interfaces are
useful when you need to implement the multiple inheritance concepts. Multiple
inheritances is only possible by interface and not by Classes (or abstract
classes) in .NET.
5. Interfaces are
slower regarding performance perspective because of additional lookup to find
out the actual implementation of the members.
6. Abstract classes
are comparatively faster than to interfaces.
7. If we do any
changes in interface (i.e. adding an additional member), then we also do
changes in that class that implemented the interface accordingly.
8. Interface can only
have methods, properties, indexers, events; it cannot have fields (variables),
constructors, and const variables.
9. Interface can have
only prototypes for members not having the implementation details.
10. Interface cannot
have access modifiers (like public, private). All members of an interface are
public and abstract by default.
11. An interface
contains only the signatures of methods, properties, events or indexers. A
class or struct that implements the interface must implement the members of the
interface that are specified in that interface definition.
Example of Abstract class and Interface;
//Abstarct
Class
public abstract class Shape
{
private string name;
public Shape(string s)
{
//
calling the set accessor of the Id property.
Id = s;
}
public string Id
{
get
{
return name;
}
set
{
name = value;
}
}
// Area
is a read-only property - only a get accessor is needed:
public abstract double Area
{
get;
}
public virtual void VirtualTest()
{
Console.WriteLine("From Shape
Class. That is abstract and parent class");
}
public abstract void AbstractTest();
public override string ToString()
{
return "Id = " + Id + ", Area =
" + string.Format("{0:F2}", Area);
}
}
//Interface
public interface Vehicles
{
string Engine
{
get;
set;
}
void Accelerator();
}
We can see abstract class contains private members also we
can put some methods with implementation also. But in case of interface only
methods and properties allowed.
This is all about the language definition. Now million
dollar question:
How can we take decision about when we have to use Interface
and when Abstract Class.
Enough theory let’s take an example.
I am trying to make a Content Management System where
content is a generalize form of article, reviews, blogs etc.
CONTENT
ARTICLE
BLOGS
REVIEW
So content is our base class now how we make a decision
whether content class should be Abstract class, Interface or normal class.
First normal class vs. other type (abstract and interface).
If content is not a core entity of my application means as per the business
logic if content is nothing in my application only Article, Blogs, Review are
the core part of business logic then content class should not be a normal
class because I’ll never make instance
of that class. So if you will never make instance of base class then Abstract
class and Interface are the more appropriate choice.
Second between Interface and Abstract Class.
As you can see content having behavior named “Publish”. If
according to my business logic Publish having some default behavior which apply
to all I’ll prefer content class as an Abstract class. If there is no default
behavior for the “Publish” and every drive class makes their own implementation
then there is no need to implement “Publish” behavior in the base case I’ll prefer Interface.
These are the in general idea of taking decision between
abstract class, interface and normal class. But there is one catch. As we all
know there is one constant in software that is “CHANGE”. If I made content
class as Interface then it is difficult to make changes in base class because
if I add new method or property in content interface then I have to implement
new method in every drive class. These problems will overcome if you are using
abstract class for content class and new method is not an abstract type. So we
can replace interface with abstract class except multiple inheritance.
CAN-DO and IS-A relationship is also define the difference
between Interface and abstract class. As we already discuss Interface can be
used for multiple inheritance for example we have another interface named
“ICopy” which having behavior copy and every drive class have to implements its
own implementation of Copy. If “Article” class drive from abstract class
Content as well as ICopy then article “CAN-DO” copy also.
IS-A is for “generalization” and “specialization” means
content is a generalize form of Article, Blogs, Review and Article, Blogs,
Review are a specialize form of Content.
So, abstract class defines core identity. If we are thinking
in term of speed then abstract is fast then interface because interface
requires extra in-direction.
So as per my view Abstract class having upper-hand in
compare to interface. Using interface having only advantage of multiple
inheritance. If you don’t understand the things then don’t worry because it’s
my mistake because I am not able to describe the topic.
Some more details with real time code example:
In C#, both abstract classes and interfaces are used to define abstract types that cannot be instantiated directly. They provide a way to define methods and properties that must be implemented by derived classes or implementing classes. However, there are key differences between the two:
Abstract Class
1. Definition: An abstract class is a class that cannot be instantiated and is often used as a base class. It can contain abstract members (methods, properties, etc.) that must be implemented in derived classes, as well as non-abstract members with implementation.
2. Members: Can include fields, constructors, destructors, properties, methods, and events.
3. Access Modifiers: Can have access modifiers for methods and properties.
4. Multiple Inheritance: A class can inherit from only one abstract class due to single inheritance.
5. Constructors: Can have constructors.
6. State: Can contain state (fields).
Interface
1. Definition: An interface is a contract that defines a set of methods and properties but provides no implementation. Any class or struct that implements the interface must implement all its members.
2. Members: Can only contain method, property, event, and indexer declarations (no fields).
3. Access Modifiers: Members of an interface are implicitly public, and they cannot have access modifiers.
4. Multiple Inheritance: A class or struct can implement multiple interfaces.
5. Constructors: Cannot have constructors.
6. State: Cannot contain state.
Real-Time Example
Consider a scenario where we have different types of employees in a company: full-time employees and contract employees. Both types of employees should have a method to calculate their salary, but the way the salary is calculated might differ.
Abstract Class Example
// Abstract Class
public abstract class Employee
{
public string Name { get; set; }
public int EmployeeId { get; set; }
// Abstract method (must be implemented in derived classes)
public abstract double CalculateSalary();
// Non-abstract method
public void DisplayEmployeeDetails()
{
Console.WriteLine($"Name: {Name}, Employee ID: {EmployeeId}");
}
}
// Derived Class - FullTimeEmployee
public class FullTimeEmployee : Employee
{
public double MonthlySalary { get; set; }
public override double CalculateSalary()
{
return MonthlySalary;
}
}
// Derived Class - ContractEmployee
public class ContractEmployee : Employee
{
public double HourlyRate { get; set; }
public int HoursWorked { get; set; }
public override double CalculateSalary()
{
return HourlyRate * HoursWorked;
}
}
Interface Example
// Interface
public interface IEmployee
{
string Name { get; set; }
int EmployeeId { get; set; }
// Method declaration
double CalculateSalary();
}
// Implementing Class - FullTimeEmployee
public class FullTimeEmployee : IEmployee
{
public string Name { get; set; }
public int EmployeeId { get; set; }
public double MonthlySalary { get; set; }
public double CalculateSalary()
{
return MonthlySalary;
}
}
// Implementing Class - ContractEmployee
public class ContractEmployee : IEmployee
{
public string Name { get; set; }
public int EmployeeId { get; set; }
public double HourlyRate { get; set; }
public int HoursWorked { get; set; }
public double CalculateSalary()
{
return HourlyRate * HoursWorked;
}
}
```
Choosing Between Abstract Class and Interface
- Use an abstract class when:
- You need to share common code among closely related classes.
- You want to provide some default behavior.
- You expect that classes will have a common base class.
- You need to define non-public members.
- Use an interface when:
- You expect that unrelated classes will implement your interface.
- You want to specify the behavior a class must implement.
- You need to take advantage of multiple inheritance.
- You want to define a contract without implementation.
By understanding these differences and use cases, you can decide whether an abstract class or an interface is more appropriate for your design needs.
(Practice Makes a Man Perfect)
No comments:
Post a Comment