Implementing Interfaces
Implementing an interface means a class signs the promise list and then actually provides every action on it. It is like a job candidate showing they can do all the tasks required.
In this page:
Syntax
class ClassName : IInterfaceName
{
public ReturnType MethodName() // every interface member needs a body
{
}
}
Implementing Interfaces
A class implements an interface by listing it after a colon and providing a concrete body for every member the interface declares. Failing to implement even one member is a compile error.
A variable typed as the interface can hold any object of a class that implements it.
Warning:
Implementing only some of an interface's members will not compile — every member is required.
Example: Implementing Interfaces
using System;
interface IShape
{
double Area();
double Perimeter();
}
class Square : IShape
{
public double Side;
public Square(double side) { Side = side; }
public double Area() => Side * Side;
public double Perimeter() => Side * 4;
}
class Program
{
static void Main(string[] args)
{
IShape shape = new Square(5);
Console.WriteLine(shape.Area());
Console.WriteLine(shape.Perimeter());
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Not implementing every member of the interface, which is a compile error.
- Implementing an interface method as non-public, which is not allowed for implicit implementations.
- Changing the signature slightly, so the method does not match the interface.
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: