Start networking and exchanging professional insights

Register now or log in to join your professional community.

Follow

Abstract class vs interface? Beside inheritance and being forced to implement all interface methods, what is the difference and when to use each?

user-image
Question added by Mostafa Mohamed , Solution Develoer , Link Development
Date Posted: 2017/02/25
Abdelrahman Mohamed
by Abdelrahman Mohamed , laravel php software developer , Dotshub

In Abstract class you can create variables and constructors but in interfaces you can't 

Nikhil Vartak
by Nikhil Vartak , Senior Software Engineer , Xoriant

Abstract class - if your entities are logically related. That is if they follow "is-a" relationship + common behavior that will be shared by all.

Ex: Saving account, Recurring account, Deposit account all derived from abstracted Account class. Interface wont be good choice here. 

Interface - If above is not true.

Ex: JSON serializer, XML serializer do not share anything in common except for the fact that they should be able Serialize and Deserialize given input. So ISerializer interface makes sense here than abstract class.

 

Mohamed Mouselhie
by Mohamed Mouselhie , Senior Software Engineer , Eshraq Group

Interface is a contract. Any class that implement a specific interface means that any object of that class have a specific operation that can be used. (i.e. any class can inherit for IComparable so we can sort any collection of that class)

Abstract class specify a family of class that share a common business. (i.e some class can inherit from base class to share some business between them like C# different Streams classes)

More Questions Like This

Do you need help in adding the right keywords to your CV? Let our CV writing experts help you.