I am going over some OO basics and trying to understand why is there a use of Interface reference variables.
When I create an interface:
public interface IWorker
{
int HoneySum { get; }
void getHoney();
}
and have a class implement it:
public class Worker : Bee, IWorker
{
int honeySum = 15;
public int HoneySum { get { return honeySum; } }
public void getHoney()
{
Console.WriteLine("Worker Bee: I have this much honey: {0}", HoneySum);
}
}
why do people use:
IWorker worker = new Worker();
worker.getHoney();
instead of just using:
Worker worker3 = new Worker();
worker3.getHoney();
whats the point of a interface reference variable when you can just instatiate the class and use it’s methods and fields that way?
If your code knows what class will be used, you are right, there is no point in having an interface type variable. Just like in your example. That code knows that the class that will be instantiated is
Worker, because that code won’t magically change and instantiate anything else thanWorker. In that sense, your code is coupled with the definition and use ofWorker.But you might want to write some code that works without knowing the class type. Take for example the following method:
That method doesn’t care about the specific class. It would handle anything that implements
IWorker.That is code you don’t have to change if you want later to use a different
IWorkerimplementation.It’s all about low coupling between your pieces of code. It’s all about maintainability.