Interfaces (intro) & multiple interface implementation
Define interfaces as contracts, implement multiple interfaces in one class, use interface-based polymorphism, and learn explicit interface implementation basics.
Interfaces overview
Goal: Program to interfaces for flexible code.
- Interfaces declare what, not how
- Implement multiple interfaces
- Pass interfaces to functions
- Explicit implementation to resolve name clashes
Implementing multiple interfaces
Interfaces define a contract. One class can implement multiple interfaces to express different roles.
using System;
public interface IPlayable
{
void Play();
}
public interface IHasDuration
{
int DurationSeconds { get; }
}
public class Song : IPlayable, IHasDuration
{
private readonly string _title;
private readonly int _seconds;
public Song(string title, int seconds)
{
_title = title;
_seconds = seconds;
}
public int DurationSeconds { get { return _seconds; } }
public void Play()
{
Console.WriteLine("Playing " + _title + " (" + _seconds + "s)");
}
}
public class Program
{
public static void Main(string[] args)
{
Song s = new Song("Hello", 5);
s.Play();
Console.WriteLine("Duration = " + s.DurationSeconds);
}
}
All lessons in this course
- virtual/override/sealed; abstract classes
- Interfaces (intro) & multiple interface implementation
- Polymorphism & dynamic dispatch