ابدأ بالتواصل مع الأشخاص وتبادل معارفك المهنية

أنشئ حسابًا أو سجّل الدخول للانضمام إلى مجتمعك المهني.

متابعة

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
تم إضافة السؤال من قبل Mostafa Mohamed , Solution Develoer , Link Development
تاريخ النشر: 2017/02/25
Abdelrahman Mohamed
من قبل Abdelrahman Mohamed , laravel php software developer , Dotshub

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

Nikhil Vartak
من قبل 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
من قبل 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)

المزيد من الأسئلة المماثلة