Implementing Interfaces
In this page:
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
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: