Multiple interfaces
Learn that a class can implement multiple interfaces.
Multiple interfaces
A class can implement more than one interface. They are separated by commas: class Button : IDrawable, IClickable. The class must implement all methods from both interfaces.
Multiple interfaces let a class take on different roles. A Button can be both drawable and clickable. Any of the interfaces can be used as the variable type: IDrawable d = new Button(); or IClickable c = new Button();. C# does not allow multiple inheritance for classes but it does for interfaces.
When to use multiple interfaces?
If a class has multiple roles, defining a separate interface for each role is a good fit. Example: a Button is both drawn and clicked; two interfaces keep the roles clear.
Prefer small, focused interfaces over a single large one. This is called the Interface Segregation Principle. A class implements only the interfaces it needs; it is not burdened with methods it doesn't use.
Exercise Button class
Define the Button class: it implements IDrawable and IClickable. The Draw method does Console.WriteLine("Drawn");, the Click method does Console.WriteLine("Clicked");. In Main, create a Button and call Draw and Click.
Show example solution
IDrawable, IClickable { public void Draw() { Console.WriteLine("Drawn"); } public void Click() { Console.WriteLine("Clicked"); } }`. In Main write `Button b = new Button(); b.Draw(); b.Click();`.
Example solution:
using System;
interface IDrawable
{
void Draw();
}
interface IClickable
{
void Click();
}
class Button : IDrawable, IClickable
{
public void Draw()
{
Console.WriteLine("Drawn");
}
public void Click()
{
Console.WriteLine("Clicked");
}
}
class Program
{
static void Main()
{
Button b = new Button();
b.Draw();
b.Click();
}
}
Test yourself
-
Fill in the blank: multiple interfaces
class Button ____ { public void Draw() { } public void Click() { } }Show answer
class Button : IDrawable, IClickable { public void Draw() { } public void Click() { } } -
Match: multiple interfaces
- comma
- interface separator
- two interfaces
- two roles
- IDrawable d = new Button()
- drawing role
- IClickable c = new Button()
- clicking role
-
Which statement about multiple interfaces is correct?
- A class can implement multiple comma-separated interfaces.
- A class can implement at most two interfaces.
- When implementing multiple interfaces, `:` is written once.
- Multiple interfaces apply only to structs.
Show answer
A class can implement multiple comma-separated interfaces. — Correct. In C# classes can implement multiple comma-separated interfaces.