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.
Because slightly closer to a real world scenario, your code would look like:
Later on when the shady geneticists invent the Crococat:
There is no need to change
Main()
orProcessAnimal()
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.