Implementing an interface
suggest changeAn interface is used to enforce the presence of a method in any class that ‘implements’ it. The interface is defined with the keyword interface
and a class can ‘implement’ it by adding : InterfaceName
after the class name. A class can implement multiple interfaces by separating each interface with a comma.
: InterfaceName, ISecondInterface
public interface INoiseMaker
{
string MakeNoise();
}
public class Cat : INoiseMaker
{
public string MakeNoise()
{
return "Nyan";
}
}
public class Dog : INoiseMaker
{
public string MakeNoise()
{
return "Woof";
}
}
Because they implement INoiseMaker
, both cat
and dog
are required to include the string MakeNoise()
method and will fail to compile without it.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents