-1

I have been gasping my head around interfaces for quite a long time and I am still unable to understand their function and what do they do. I read thousands of forum posts and I keep asking myself a single question. I will explain to you what the question I am asking is.

We have got this core, which does a really simple thing. We take one class, and in the main class we call the function declared in that class, by using an interface.

public interface IAnimal
{
   string GetDescription();
}

class Cat : IAnimal
{     
   public string GetDescription()
   {
      return "I'm a cat";
   }
}

class Program
{
    static void Main(string[] args)
    {
       Cat myCat = new Cat();

       Console.WriteLine(myCat.GetDescription());
    }
}

The question I keep asking myself. Why are we doing this? What is the point? Why not simply do this:

class Cat
{     
   public static string GetDescription()
   {
      return "I'm a cat";
   }
}

class Program
{
    static void Main(string[] args)
    {
    Cat.GetDescription();
    }
}

I would greatelly appreciate any help and a PROPER explanation. I am open for simple accurate examples. Nothing too complex. I would also like you to provide some text and explain why is this and that there.

Thank you.

EDIT: I am sorry for confusing some people. In the second description I forgot to change public void cat to public static void cat, therefore it was unaccessable and did not compile.

Erik9631
  • 87
  • 9
  • Your second example does not even compile. `GetDescription()` is not a static method and you are trying to use it as one – dotnetom Jun 14 '15 at 20:15
  • 2
    You probably didn't read any good material then. Interfaces are a key software design concept, that has unlimited amount of good examples. – Amit Jun 14 '15 at 20:17
  • What if you are a dog..? – Nicklas Pouey-Winger Jun 14 '15 at 20:18
  • "We take one class" - there's your problem. Interfaces are mostly useful when you have multiple classes. Also, it doesn't help to use such contrived examples when you're trying to understand what real world use the feature is. – Blorgbeard Jun 14 '15 at 20:19
  • There are a LOT of reasons why. One possible answer is that languages that define interfaces may limit the class inheritance to one parent per class, and avoid problems like a "diamond inheritance": https://en.wikipedia.org/wiki/Multiple_inheritance – MaMazav Jun 14 '15 at 20:20
  • 1
    This is not a simple concrete question. It requires a tutorial in OO design principles, this is not the right place. – H H Jun 14 '15 at 20:21
  • Also, your first example is not even using the interface. The point is that you can get a return value of type `IAnimal` from somewhere, and not have to care about what concrete type it is, just that it implements `IAnimal`. It could be Cat, Dog, Tiger, whatever. If your code only cares about the interface, it only has to deal with the interface. – Blorgbeard Jun 14 '15 at 20:25

2 Answers2

1

This question is asked by many new programmers and you will get several answers for it. I am a Computer Science student and I will try my best to explain this to you.

Interface provides alternative to multiple inheritance. C# allows you to inherent from only one single base class but we can implement as many interfaces as we want.

The example you posted above has a class Cat which implements an interface IAnimal. This is little bit wrong in my opinion because you should use Animal as an abstract class. Pragmatically this will not make any difference butt the concept which you are trying to use here is of inheritance (A cat inherit from Animal). Following line is from MSD:

if the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.

So now you might be thinking then what are the real purpose of interfaces and when to use them. Answer is simple, use interfaces when you want to impose some kind of restrictions to the users of your interface (or other developers who implements your interface) or want to extract common things from several classes.

A nice example for use of inheritance and interfaces will be:

Lets say you are building a software for electronics devices. And the scenario is like (parent class -> inherited class) : Gadgets -> Electronic Gadgets -> Telephony Gadgets -> Mobiles -> Smart Phones -> Tablest

And say Mobiles, Smart Phones and tablets have a common feature of FM-RADIO. This feature is available in other Gadgets which are not Telephony Gadgets. Now it will be perfect to use FM-Radio as an interface. Every gadget will provide their own definition of FM-Radio but all will share same functionality.

Hope I have cleared your confusion.

Zain Zafar
  • 1,607
  • 4
  • 14
  • 23
  • So we have got FM-RADIO function which is available in all other gadgets, sure but what is the point of making ONLY a prototype. You do not save anything, you do not gain anything. Why not just delcare the function without the interface? It would save time. I do not understand. – Erik9631 Jun 15 '15 at 13:18
  • Good question. There are two reasons for that. First is we want our code as much *Object Oriented* as possible. Interfaces help in that. Another reason which I have mentioned earlier is the idea of imposing restriction. In this example, the FM-Radio interface will help us to ensure that every gadget follows a same design pattern . This unified design will help us to apply `polymorphism`. For instance we want to tune all the devices to a specific channel. We would call a same method (of interface) on every device and all of them will be tuned accordingly. – Zain Zafar Jun 15 '15 at 13:38
0

Because slightly closer to a real world scenario, your code would look like:

static void Main(string[] args)
{
    List<IAnimal> animals = GetAllZooAnimals();
    foreach (IAnimal animal in animals)
        ProcessAnimal(animal);
}

static void ProcessAnimal(IAnimal animal)
{
     Console.WriteLine(animal.GetDescription());
}

Later on when the shady geneticists invent the Crococat:

public class Crococat : IAnimal
{
    public string GetDescription()
    {
        return "I'm a horrible concoction that looks like a furry crocodile with whiskers and paws.";
    }
}

There is no need to change Main() or ProcessAnimal() just because GetAllZooAnimals() return a type of animal never before seen. Since these only care about the generic properties available for all animals, it reduces the changes we need to make to the program code as new animals are invented.

Oskar Berggren
  • 5,583
  • 1
  • 19
  • 36