Abstract Classes vs Interfaces

This is one of the most common interview questions asked and ironically is answered a lot badly. I will try to explain the differences from my understanding.
1. An abstract class cannot be instantiated independently from its derived class. However its constructor can be called by the derived class. But in case of an interface, it cannot be instantiated and in fact cannot contain any constructor/finalizer.
2. While creating an abstract class, method’s implementation can be provided which the derived class may override, however no implementation is present in an interface member’s declaration. All the implementation of an interface members must be provided by the deriving classes.
3. Abstract classes are more extensible as they do not break any version compatibility when a non-abstract method is added to an abstract class, but an interface would always break code-version compatibility upon modification as the deriving classes won’t compile until additional implementations.
4. Abstract classes can contain data stored in fields whereas interfaces cannot store any data, although properties can be defined but without any implementation.
5. Deriving from an abstract class would use up the subclass’s one and only base class option, however by implementing interfaces it can still inherit from a class.

When we talk about abstract classes we are defining characteristics of an object type, specifying what an object is but in the case of an interface we define a capability and we bond to provide that capability, we are talking about establishing a contract about what the object can do.

Hope this helps in understanding further about the differences in abstract classes and interfaces, and where and when to use whom.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.