C#
Implementing interfaces
Learn how a class implements an interface.
Implementing an interface
To implement an interface a class writes : and the interface name: class Rectangle : IShape. This means the class will provide all the interface's methods.
In the implementing class, each method is written as public with a body. If a method is missing, you get a compile error. An interface-typed variable can hold an instance of an implementing class: IShape s = new Rectangle();. This is the basis of polymorphism.
Using interface types
An interface acts as a common type for implementing classes. Writing IShape s = new Rectangle(); makes the variable s see only the IShape members.
This way different classes can share a collection: List<IShape>. A call s.Area() always runs the right class's method. This behavior is called polymorphism and is covered in depth in later groups.
Exercise Rectangle area
Define the Rectangle class: it implements IShape and has public int Width { get; set; } and public int Height { get; set; } properties. The public int Area() method returns Width * Height. In Main, create IShape s = new Rectangle { Width = 3, Height = 4 }; and print s.Area().
Show example solution
IShape { public int Width { get; set; } public int Height { get; set; } public int Area() { return Width * Height; } }`. In Main write `IShape s = new Rectangle { Width = 3, Height = 4 }; Console.WriteLine(s.Area());`.
Example solution:
using System;
interface IShape
{
int Area();
}
class Rectangle : IShape
{
public int Width { get; set; }
public int Height { get; set; }
public int Area()
{
return Width * Height;
}
}
class Program
{
static void Main()
{
IShape s = new Rectangle { Width = 3, Height = 4 };
Console.WriteLine(s.Area());
}
}
Test yourself
-
Match: implements parts
- : IShape
- implementation syntax
- public
- implementing method access
- IShape s = new Rectangle()
- interface-typed variable
- missing method
- compile error
-
Which statement about implementing interfaces is correct?
- The `implements` keyword is used.
- A class can implement only one interface.
- Implementation uses `:` and the interface name.
- An implementing class can hide methods.
Show answer
Implementation uses `:` and the interface name. — Correct. In C# implementation is done with `: InterfaceName`.
-
Fill in the blank: implements declaration
class Rectangle ____
{
public int Width { get; set; }
public int Height { get; set; }
}
Show answer
class Rectangle : IShape
{
public int Width { get; set; }
public int Height { get; set; }
}
Next lesson: Multiple interfaces