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

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

متابعة

Why do we use interfaces; why not to use classes instead of interfaces as there is only declaration in interface?

user-image
تم إضافة السؤال من قبل Atif Gulzar , Web Developer , Ethos Integrated Solutions
تاريخ النشر: 2013/10/07
Ahmad Anbari
من قبل Ahmad Anbari , Software System Engineer , Continental Jet Services FZCO

The very important point in using interface is: there is no inheritance. As you know, programming languages like Java, C#, VB don’t support multiple-inheritance; meaning a class can inherit from one class only.

Let’s say you write a code for counting a collection and the method signature is as follow:

public static void Count(ICollection collection);

Your method expects two functions from the collection object: GoToFirst, GoNext.

 

If I have a class called MyCollection which inherit from class called ArrayList and would like to use your count method, all I have to do is implement the two methods.

 

The concept behind Interface is very similar to abstract classes, but it eliminates the need to inherit from a class.

This way a class can play multiple roles while inheriting from one class only.

Deepak Mishra
من قبل Deepak Mishra , Lead Developer , Chevron

Check this code and reply if you got the answer:

interface Iperson   

{        int Subscribe();   

}   

class Program  

  {        static void Main(string[] args)       

{            List pl = new List();           

Iperson person1 = new Customer();           

Iperson person2 = new Employee();           

pl.Add(person1);           

pl.Add(person2);           

foreach (Iperson i in pl)              

Console.WriteLine( i.Subscribe());           

Console.Read();      

  }   

}   

class Customer : Iperson   

{       

public int Subscriber { get; private set; }       

public int Subscribe()       

{           

Subscriber =0;           

return Subscriber;

}   

}   

class Employee : Iperson   

{       

public int Subscriber { get; private set; }       

public int Subscribe()      

 {

Subscriber =1;

return Subscriber;

}   

}

Samuel Eid Safwat Naguib
من قبل Samuel Eid Safwat Naguib , Technology lead ,Project Manager ,Transformation Coach , Octalpha

Interfaces don't support implementation, so you cannot supply any default implementations as you can with abstract classes. Additionally, interfaces are not restricted to hierarchies, so they are more flexible than abstract classes.

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

هل تحتاج لمساعدة في كتابة سيرة ذاتية تحتوي على الكلمات الدلالية التي يبحث عنها أصحاب العمل؟