An interface in computer science is a mechanism for specifying a contract between different software components, without specifying the implementation details. It defines a set of methods and properties that a class implementing the interface must provide, but does not specify how those methods should be implemented. This allows for flexibility and reusability of code, as well as the ability to use different implementations of the same interface in different situations.
An example of an interface can be found below.
For this example we’ll define an Animal class, and have two animals inherit from this class. One animal will be a dog and the other will be a cat:
public class Animal
{
public string Name { get; set; }
public Animal(string name)
{
Name = name;
}
public virtual string MakeSound()
{
return "Default Animal Sound.";
}
}
This Interface for this class will look like this, which encapsulates all the logic and displays only the methods and parameters that we are concerned about:
interface IAnimal
{
string Name { get; set; }
string MakeSound();
}
Next we can create a dog and a cat class which inherit from the Animal Class like so:
class Dog : IAnimal
{
public string Name { get; set; }
public override string MakeSound()
{
return "Woof!";
}
}
class Cat : IAnimal
{
public string Name { get; set; }
public override string MakeSound()
{
return "Meow!";
}
}
In the code above we can override the MakeSound() method in the animal class to return a sound that the animal should make. In the Dogs case we return “Woof!” and in the Cats case we return “Meow!”.
Resources: