interface vs abstract
Learn the difference between interface and abstract class.
interface vs abstract class
An interface is a contract; it cannot hold fields and contains only method signatures (plus default methods from C# 8). An abstract class can hold both bodied and bodyless methods and fields; it provides partial implementation.
A class can inherit only one abstract class but implement multiple interfaces. An interface represents a "can-do" relationship, an abstract class an "is-a" relationship. Example: Song is a Media (abstract) and is IPlayable (interface).
Using them together
In C# a class can inherit an abstract class and implement multiple interfaces at the same time. Order: abstract class first, then interfaces. Example: class Song : Media, IPlayable, ICloneable.
This pattern is useful to take common behavior from the abstract class and add capabilities with interfaces. Media holds fields and methods common to all media types; IPlayable adds the play capability as a contract.
Exercise Song class
Add a public abstract void Stop(); method to Media. In Song write the public override void Stop() body: Console.WriteLine("Stopped");. In Main, create a Song and call Play and Stop.
Show example solution
Add `public abstract void Stop();` to Media. Add `public override void Stop() { Console.WriteLine("Stopped"); }` to Song. In Main write `Song s = new Song(); s.Play(); s.Stop();`.
Example solution:
using System;
interface IPlayable
{
void Play();
}
abstract class Media
{
public abstract void Stop();
}
class Song : Media, IPlayable
{
public void Play()
{
Console.WriteLine("Playing");
}
public override void Stop()
{
Console.WriteLine("Stopped");
}
}
class Program
{
static void Main()
{
Song s = new Song();
s.Play();
s.Stop();
}
}
Test yourself
-
Match: interface vs abstract
- interface
- contract
- abstract class
- partial implementation
- multiple
- interface
- single
- abstract class
-
Which statement about interface vs abstract is correct?
- An interface can hold fields, an abstract class cannot.
- An interface is for contracts, an abstract class for shared behavior.
- A class can implement only one interface but inherit multiple abstract classes.
- An interface and an abstract class are the same thing.
Show answer
An interface is for contracts, an abstract class for shared behavior. — Correct. An interface is for contracts, an abstract class for shared behavior.
-
Fill in the blank: abstract method
abstract class Media { public ____ void Stop(); }Show answer
abstract class Media { public abstract void Stop(); }